You are on page 1of 19

Subject: Programming with Python Class: TYCM

Unit 3: Data Structures in Python (14


Marks )

1.1 List
1.2 Tuples
1.3 Sets
1.4 Dictionaries

1
Tuple in Python:
3.2.1 Defining Tuples,
accessing values in Tuples,
deleting values in Tuples,
updating Tuples.
3.2.2 Basic Tuple Operations
3.2.3 Built - in Tuple functions
# Difference between List & Tuple

2
# Difference between List & Tuple:
SN List Tuple
The literal syntax of List is shown by the The literal syntax of the tuple is shown by
1
[]. the ().
2 The List is mutable. The tuple is immutable.
3 The List has the variable length. The tuple has the fixed length.
The List provides more functionality The tuple provides less functionality than
4
than tuple. the Tuple.
The tuple is used in the cases where we
The List is used in the scenario in which
need to store the read-only collections
we need to store the simple collections
5 i.e., the value of the items can not be
with no constraints where the value of
changed. It can be used as the key inside
the items can be changed.
the dictionary.
Tuple does not have must built-in
6 Lists have several built-in methods
methods.
Tuple consume less memory as
7 List consume more memory
compared to the Tuple 3
Tuple in Python: Defining Tuple
The Tuple is a datatype available in Python which can be
written as a collection of comma-separated values (items)
between rounded brackets (Paranthesis).
Items in a Tuple need not be of the same type.
Example
Tup=( ) #Empty Tuple
Tuple1 = ('physics', 'chemistry', 1997, 2000)
Tuple2 = (1, 2, 3, 4, 5 )
Tuple3 = ("a", "b", "c", "d“)
In Python programming, a Tuple is created by
placing all the items (elements) inside a round
bracket ( ), separated by commas.
4
Tuple in Python: Defining Tuples
It can have any number of items and they may be of
different types (integer, float, string etc.).
# empty Tuple
my_Tuple =( )
# Tuple of integers
my_Tuple = (1, 2, 3)
# Tuple with mixed datatypes
my_Tuple = (1, "Hello", 3.4)
Also, a Tuple can even have another Tuple as an item. This
is called nested Tuple.
# nested Tuple
My_t=(1,"kkwp", 12.36, 'a',(1,2,3), 78)
5
Tuple in Python: Accessing values in Tuple
There are various ways in which we can access the elements
of a Tuple.
We can use the index operator [ ] to access an item in a
Tuple.
Index starts from 0. So, a Tuple having 5 elements will have
index from 0 to 4.
Trying to access an element other that this will raise an
IndexError.
The index must be an integer.
We can't use float or other types, this will result into
TypeError.
Nested Tuple are accessed using nested indexing.
A Tuple may also contain tuples or so.
6
Tuple in Python: Accessing values in Tuple
Note:

1. TypeError:
If you do not use integer indexes in the tuple. For
example my_data[2.0] will raise this error. The index
must always be an integer.

2. IndexError:
Index out of range. This error occurs when we mention
the index which is not in the range. For example, if a
tuple has 5 elements and we try to access the 7th
element then this error would occur.

7
Tuple in Python: Accessing values in Tuple
my_Tuple = ('p','r','o','b','e‘)
print(my_Tuple[0]) # Output: p
print(my_Tuple[2]) # Output: o
print(my_Tuple[4]) # Output: e
# Error! Only integer can be used for indexing
my_Tuple[4.0]
# Nested Tuple
n_Tuple = ("Happy", (2,0,1,5))
# Nested indexing
print(n_Tuple[0][1]) # Output: a
print(n_Tuple[1][3]) # Output: 5

8
Tuple in Python: Slicing Tuples
We can access a range of items in a Tuple by using the
slicing operator : (colon).
my_Tuple = ('p','r','o','b','l','e','m')

# elements 3rd to 5th


print(my_Tuple[2:5]) Output:['o', 'b', 'l']

# elements 6th to end


print(my_Tuple[5:]) Output:['e', 'm']

9
Tuple in Python:
Tuple with only single element:
Note: When a tuple has only one element, we must put a
comma after the element, otherwise Python will not treat
it as a tuple.
# a tuple with single data item
my_data = (99,)

If we do not put comma after 99 in the above example then


python will treat my_data as an int variable rather than a tuple.

10
Tuple in Python: Negative indexing
my_Tuple = ('p','r','o','b','e‘)
# Output: e
print(my_Tuple[-1])
# Output: p
print(my_Tuple[-5])

11
Tuple in Python: Negative indexing
◻ str1=['p','r','o','b','l','e','m']
◻ print(str1[-5:-2:1]);
◻ output-['o', 'b', 'l'] Step plus

◻ print(str1[-5:-2:-1]);
◻ output-[] no selection

◻ print(str1[-5:-7:-1]);
◻ output-['o', 'r'] Step plus
12
Tuple in Python: Deleting Values in Tuples
Removing individual tuple elements is not possible in
tuple.
We can use another tuple with the undesired elements
discarded.
To explicitly remove an entire tuple, just use the del
statement.
For example −
tup = ('physics', 'chemistry', 1997, 2000)
del tup;

13
Tuple in Python: Updating Tuples
Unlike lists, tuples are immutable.
This means that elements of a tuple cannot be changed
once it has been assigned.
But, if the element is itself a mutable datatype like list,
its nested items can be changed.
We can also assign a tuple to different values
(reassignment).
t3=(1,2,[4,5,6],7)
t3[2][1]=11
print(t3)
(1, 2, [4, 11, 6], 7)
14
Tuple in Python: Basic Tuple Operation
Tuples respond to the + and * operators much like strings;
they mean concatenation and repetition here too, except that
the result is a new Tuple, not a string.
In fact, Tuples respond to all of the general sequence
operations we used on strings in the prior chapter.
Python Expression Results Description
len((1, 2, 3)) 3 Length
(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation
('Hi!‘)* 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!‘) Repetition
3 in (1, 2, 3) True Membership
for x in (1, 2, 3): print x, 123 Iteration

15
Tuple in Python: Updating Tuples
Example
odd = (1, 3, 5)
print(odd + [9, 7, 5]) # Output: [1, 3, 5, 9, 7, 5]
print(["re"] * 3) #Output: ["re", "re", "re"]

t3=(1, 2, [4, 11, 6], 7)


t4=t3+(5,6)
Print(t4) #O/P (1, 2, [4, 11, 6], 7, 5, 6)

t4=t3+[55,66]
Traceback (most recent call last): File "<pyshell>", line 1, in
<module> TypeError: can only concatenate tuple (not "list")
to tuple
16
Tuple in Python: Built-in Functions
Sr.
Function Description
No.

It compares two tuples and returns true if tuple1 is


1 cmp(tuple1, tuple2) greater than tuple2 otherwise false.
(Only for Python Version 2.X)

2 len(tuple) It calculates the length of the tuple.


3 max(tuple) It returns the maximum element of the tuple.
4 min(tuple) It returns the minimum element of the tuple.
5 tuple(seq) It converts the specified sequence to the tuple.
6 sum(tuple) Returns sum of all elements in tuple
7 any(tuple) Return true if any value in tuple is greater than one
8 all(tuple) Return true if all values in tuple are greater than one

17
Tuple in Python: Built-in Functions
Example Example
>>> t=(8,7,1,2,3,9,4,5,6) >>> any(t)
>>> t True
(8, 7, 1, 2, 3, 9, 4, 5, 6) >>> all(t)
>>> len(t) True
9 >>> l=[2,3,4,5,2,3,4,5]
>>> min(t) >>> t1=tuple(l)
1 >>> t1
>>> max(t) (2, 3, 4, 5, 2, 3, 4, 5)
9 >>> l
>>> sorted(t) [2, 3, 4, 5, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> sum(t)
45

18
Tuple in Python: Built-in Methods

Sr. Description
Methods
No.
Returns count of how many times obj
occurs in Tuple
1 Tuple.count(obj) >>> t=(1,2,3,4,1,6,1)
>>> t.count(1)
3
Returns the lowest index in Tuple that obj
appears
2 Tuple.index(obj) >>> t=(1,2,3,4,1,6,1)
>>> t.index(6)
5

19

You might also like