TUPLE IN PYTHON
8.1 INTRODUCTION:
Tuple is a collection of elements which is ordered and unchangeable (Immutable).
Immutable means you cannot change elements of a tuple in place.
Allows duplicate members.
Consists the values of any type, separated by comma.
Tuples are enclosed within parentheses ( ).
Cannot remove the element from a tuple.
8.2 Creating Tuple:
Syntax:
tuple-name = ( ) # empty tuple
tuple-name = (value-1, value-2,............, value-n)
Example:
>>> T=(23, 7.8, 64.6, 'h', 'say')
>>> T
(23, 7.8, 64.6, 'h', 'say')
8.2.1 Creating a tuple with single element:
>>> T=(3) #With a single element without comma, it is a value only, not a tuple
>>> T
>>> T= (3, ) # to construct a tuple, add a comma after the single element
>>> T
(3,)
>>> T1=3, # It also creates a tuple with single element
>>> T1
(3,)
8.2.2 Creating a tuple using tuple( ) constructor:
o It is also possible to use the tuple( ) constructor to create a tuple.
>>>T=tuple( ) # empty tuple
>>> T=tuple((45,3.9, 'k',22)) #note the double round-brackets
>>> T
(45, 3.9, 'k', 22)
>>> T2=tuple('hello') # for single round-bracket, the argument must be of sequence type
>>> T2
('h', 'e', 'l', 'l', 'o')
>>> T3=('hello','python')
>>> T3
('hello', 'python')
8.2.3 Nested Tuples:
>>> T=(5,10,(4,8))
>>> T
(5, 10, (4, 8))
8.2.4 Creating a tuple by taking input from the user:
>>> T=tuple(input("enter the elements: "))
enter the elements: hello python
>>> T
('h', 'e', 'l', 'l', 'o', ' ', 'p', 'y', 't', 'h', 'o', 'n')
>>> T1=tuple(input("enter the elements: "))
enter the elements: 45678
>>> T1
('4', '5', '6', '7', '8') # it treats elements as the characters though we entered digits
To overcome the above problem, we can use eval( ) method, which identifies the
data type and evaluate them automatically.
>>> T1=eval(input("enter the elements: "))
enter the elements: 56789
>>> T1
56789 # it is not a list, it is an integer value
>>> type(T1)
<class 'int'>
>>> T2=eval(input("enter the elements: "))
enter the elements: (1,2,3,4,5) # Parenthesis is optional
>>> T2
(1, 2, 3, 4, 5)
>>> T3=eval(input("enter the elements: "))
enter the elements: 6, 7, 3, 23, [45,11] # list as an element of tuple
>>> T3
(6, 7, 3, 23, [45, 11])
8.3 Accessing Tuples:
Tuples are very much similar to lists. Like lists, tuple elements are also indexed.
Forward indexing as 0,1,2,3,4……… and backward indexing as -1,-2,-3,-4,………
The values stored in a tuple can be accessed using the slice operator ([ ] and [:]) with
indexes.
tuple-name[start:end] will give you elements between indices start to end-1.
The first item in the tuple has the index zero (0).
Example:
>>> alpha=('q','w','e','r','t','y')
Forward Index
0 1 2 3 4 5
q w e r t y
-6 -5 -4 -3 -2 -1
Backward Index
>>> alpha[5]
'y'
>>> alpha[-4]
'e'
>>> alpha[46]
IndexError: tuple index out of range
>>> alpha[2]='b' #can’t change value in tuple, the value will remain
unchanged TypeError: 'tuple' object does not support item assignment
8.3.1 Difference between List and Tuple:
S. No. List Tuple
1 Ordered and changeable (Mutable) Ordered but unchangeable (Immutable)
2 Lists are enclosed in brackets. [] Tuples are enclosed in parentheses. ( )
3 Element can be removed. Element can’t be removed.
8.4 Traversing a Tuple:
Syntax:
for <variable> in tuple-name:
statement
Example:
Method-1
>>> alpha=('q','w','e','r','t','y')
>>> for i in alpha:
print(i)
Output:
q
w
e
r
t
y
Method-2
>>> for i in range(0, len(alpha)):
print(alpha[i])
Output:
q
w
e
r
t
y
8.5 Tuple Operations:
Joining operator +
Repetition operator *
Slice operator [:]
Comparison Operator <, <=, >, >=, ==, !=
Joining Operator: It joins two or more tuples.
Example:
>>> T1 = (25,50,75)
>>> T2 = (5,10,15)
>>> T1+T2
(25, 50, 75, 5, 10, 15)
>>> T1 + (34)
TypeError: can only concatenate tuple (not "int") to tuple
>>> T1 + (34, )
(25, 50, 75, 34)
Repetition Operator: It replicates a tuple, specified number of times.
Example:
>>> T1*2
(25, 50, 75, 25, 50, 75)
>>> T2=(10,20,30,40)
>>> T2[2:4]*3
(30, 40, 30, 40, 30, 40)
Slice Operator:
tuple-name[start:end] will give you elements between indices start to end-1.
>>>alpha=('q','w','e','r','t','y')
>>> alpha[1:-3] ('w',
'e')
>>> alpha[3:65] ('r',
't', 'y')
>>> alpha[-1:-5]
()
>>> alpha[-5:-1]
('w', 'e', 'r', 't')
List-name[start:end:step] will give you elements between indices start to end-1 with
skipping elements as per the value of step.
>>> alpha[1:5:2]
('w', 'r')
>>> alpha[ : : -1]
('y', 't', 'r', 'e', 'w', 'q') #reverses the tuple
Comparison Operators:
o Compare two tuples
o Python internally compares individual elements of tuples in lexicographical
order.
o It compares the each corresponding element must compare equal and two
sequences must be of the same type.
o For non-equal comparison as soon as it gets a result in terms of True/False,
from corresponding elements’ comparison. If Corresponding elements are
equal, it goes to the next element and so on, until it finds elements that differ.
Example:
>>> T1 = (9, 16, 7)
>>> T2 = (9, 16, 7)
>>> T3 = ('9','16','7')
>>> T1 = = T2
True
>>> T1==T3
False
>>> T4 = (9.0, 16.0, 7.0)
>>> T1==T4
True
>>> T1<T2
/ Page 7
False
>>> T1<=T2
True
8.6 Tuple Methods:
Consider a tuple:
subject=("Hindi","English","Maths","Physics")
S. Function
No.
Description Example
Name
1 len( ) Find the length of a tuple. >>>subject=("Hindi","English","Maths","Physics”)
Syntax: >>> len(subject)
len (tuple-name) 4
2 max( ) Returns the largest value >>> max(subject)
from a tuple. 'Physics'
Syntax:
max(tuple-name)
Error: If the tuple contains values of different data types, then it will give an error
because mixed data type comparison is not possible.
>>> subject = (15, "English", "Maths", "Physics", 48.2)
>>> max(subject)
TypeError: '>' not supported between instances of 'str' and 'int'
3. min( ) Returns the smallest >>>subject=("Hindi","English","Maths","Physics")
value from a tuple. >>> min(subject)
Syntax:
min(tuple-name) 'English'
Error: If the tuple contains values of different data types, then it will give an error
because mixed data type comparison is not possible.
>>> subject = (15, "English", "Maths", "Physics", 48.2)
>>> min(subject)
TypeError: '>' not supported between instances of 'str' and 'int'
4 index( ) Returns the index of the >>>subject=("Hindi","English","Maths","Physics")
first element with the
specified value.
Syntax:
Page 8
tuple- >>> [Link]("Maths")
[Link](element)
2
5 count( ) Return the number of >>> [Link]("English")
times the value appears.
Syntax: 1
tuple-
[Link](element)
8.7 Tuple Packing and Unpacking:
Tuple Packing: Creating a tuple from set of values.
Example:
>>> T=(45,78,22)
>>> T
(45, 78, 22)
Tuple Unpacking : Creating individual values from the elements of tuple.
Example:
>>> a, b, c=T
>>> a
45
>>> b
78
>>> c
22
Note: Tuple unpacking requires that the number of variable on the left side must be equal
to the length of the tuple.
8.8 Delete a tuple:
The del statement is used to delete elements and objects but as you know that tuples are
immutable, which also means that individual element of a tuple cannot be deleted.
Page 9
Example:
>> T=(2,4,6,8,10,12,14)
>>> del T[3]
TypeError: 'tuple' object doesn't support item deletion
But you can delete a complete tuple with del statement as:
Example:
>>> T=(2,4,6,8,10,12,14)
>>> del T
>>> T
NameError: name 'T' is not defined
Page 10
Page 11