Tuples in Python
Introduction
Tuples are used to store multiple items in a single
variable.
The Python tuples are sequences that are used to
store a tuple of values of any type. such as
integer, float, string, list or even a tuple.
Python tuples are immutable i.e., you cannot
change the elements of a tuple in place.
Elements of a tuple are enclosed in parenthesis()
(round brackets) and are separated by commas.
Creating a Tuple
Syntax:
Variable_Name =(elements,.,.,….)
(Tuple_Name)
Example: T=(1,2,3,4,5)
Creating a Tuple
T= ( ) empty tuple
T=( 1, 2, 3 ) tuple of integers
T=( ‘a’, ‘b’, ‘c’ ) tuple of characters
T=( ‘one’, ‘two’, ‘three’ ) tuple of strings
T=(1,”RAM”,5.5) tuple of mixed data types
Tuple can be created by putting the no. of expressions in
parentheses. Use round brackets to indicate the start and
end of the tuple, and separate the items by commas.
Example
#tuple1 is the tuple of integers
>>> tuple1 = (1,2,3,4,5)
>>> tuple1
(1, 2, 3, 4, 5)
#tuple2 is the tuple of mixed data types
>>> tuple2 =('Economics',87,'Accountancy',89.6)
>>> tuple2
('Economics', 87, 'Accountancy', 89.6)
#tuple3 is the tuple with list as an element
>>> tuple3 = (10,20,30,[40,50])
>>> tuple3
(10, 20, 30, [40, 50])
#tuple4 is the tuple with tuple as an element
>>> tuple4 = (1,2,3,4,5,(10,20))
>>> tuple4
(1, 2, 3, 4, 5, (10, 20))
Creating Tuples from Existing Sequence
T = tuple(<sequence>)
where <sequence> can be any kind of sequence
object including strings, lists and tuples.
Python creates the individual elements of the
tuple from the individual elements of passed
sequence.
T = tuple(‘hello’)
print(T )
( ‘h’, ‘e’, ‘l’, ‘l’, ‘o’ )
Empty Tuple
a=()
a=a+(33516140,44738484)
print(a)
Nested Tuples
If a tuple contains an element which is a tuple itself
then it is called a nested tuple, e.g.,
T = ( 1, 2, ( 3, 4 ) )
The no. of elements in T is 3 : 1, 2 and ( 3, 4 )
Single Element Tuple
If there is only a single element in a tuple then the element
should be followed by a comma. If we assign the value
without comma it is treated as integer.
#incorrect way of assigning single element to tuple
#tuple5 is assigned a single element
>>> tuple5 = (20)
>>> tuple5
20
>>>type(tuple5) #tuple5 is not of type tuple
<class 'int'> #it is treated as integer
#Correct Way of assigning single element to tuple
#tuple5 is assigned a single element
>>> tuple5 = (20,) #element followed by comma
>>> tuple5
(20,)
>>>type(tuple5) #tuple5 is of type tuple
<class 'tuple'>
#a sequence without parentheses is treated as tuple by default
>>> seq = 1,2,3 #comma separated elements
>>> type(seq) #treated as tuple
<class 'tuple'>
>>> print(seq) #seq is a tuple
(1, 2, 3)
Difference Between tuple and list
List Tuple
Mutable (we can Change the elements in the Immutable (we Cannot change elements in
list) the tuple)
Elements are enclosed in square brackets [] enclosed in parenthesis ()
[1,2,3] (1,2,3)
We can use the method (like append(), We can not use methods (like append(),
insert(), extend() ) to change the elements insert(), extend() ) to change the element
in the list. in the same Tuple.
Assigning Values: Assigning Values:
L[i]=element # Valid in list T[i]=element # it is invalid, you can
L=[1,2,3] >>>l[1]=4 not perform item-assignment in immutable
>>>L 1,4,3 types.
Similarity with Lists
Length- Function len(T) returns the no. of items in the tuple
T.
Indexing - T[i] returns the item at index i(the first item has
index 0)
Slicing - T[a:b] returns a new tuple, containing the objects
at indexes between a and b(excluding b)
T[a:b:c] returns a new tuple containing every nth term from
index a to b, excluding b.
Concatenation
The + operator adds one tuple to the end of another.
replication operator *
The * operator repeats a tuple.
Membership operator: both ‘in’ and ‘not in’ operators
work on tuples just like they work for other sequences.
‘in’ tells if an element is present in the tuple or not and
‘not in’ does the opposite.
Accessing Individual Elements of Tuples
The individual elements of a Tuples are
accessed through their indexes. Tuples elements
are indexed, i.e., forward indexing as
0,1,2,3,…. And backward indexing as -1,-2,-
3,….
vowels = (‘a’, ‘e’, ‘i’, ‘o’, ‘u’ )
vowels[0] #a
vowels[4] #u
vowels[-5] #a
Traversing a Tuple
Traversal of a sequence means accessing and processing
each elements of it. for loop makes it easy to traverse the
items in a tuple.
Example:
T=('P','Y','T','H','O','N') P
for a in T: Y
print(a,end=‘’) T
Output: H
PYTHON O
N
NEXT TOPIC
Joining, Replicating and Slicing of Tuples
The concatenation operator +, when used with tuples, join two tuples. Only
two tuples can be joined.
tpl1,tpl2 = ( 10, 20, 34 ), ( 6, 3, 67 )
tpl1+tpl2 = ( 10, 20, 34, 6, 3, 67 )
tpl1 + 3 #type error
tpl1 + (3) #type error
tpl1 + (3,)
>>>tpl1
( 10, 20, 34, 3)
The * operator replicate a tuple specified no. of times.
tpl1= ( 10, 20, 34 ),
Tpl1*2 => ( 10, 20, 34, 10, 20, 34 )
Tuple slices are the sub part of a tuple extracted out. The tuple slice is
itself a tuple.
T1 =( 10, 12, 13, 20, 25, 29, 20, 48 )
seq= T1[3:7] seq=>( 20, 25, 29, 20 )
Concatenation
Concatenation operator can be used for extending an
existing tuple. When we extend a tuple using
concatenation a new tuple is created.
>>> tuple6 = (1,2,3,4,5)
#single element is appended to tuple6
>>> tuple6 = tuple6 + (6,)
>>> tuple6
(1, 2, 3, 4, 5, 6)
#more than one elements are appended
>>> tuple6 = tuple6 + (7,8,9)
>>> tuple6 (1, 2, 3, 4, 5, 6, 7, 8, 9)
Slicing Tuples with examples
Like string and list, slicing can be applied to tuples also.
#tuple1 is a tuple
>>> tuple1 = (10,20,30,40,50,60,70,80)
#elements from index 2 to index 6
>>> tuple1[2:7]
(30, 40, 50, 60, 70)
#all elements of tuple are printed
>>> tuple1[0:len(tuple1)]
(10, 20, 30, 40, 50, 60, 70, 80)
#slice starts from zero index
>>> tuple1[:5]
(10, 20, 30, 40, 50)
#slice is till end of the tuple
>>> tuple1[2:]
(30, 40, 50, 60, 70, 80)
#step size 2
>>> tuple1 = (10,20,30,40,50,60,70,80)
>>> tuple1[0:len(tuple1):2]
(10, 30, 50, 70)
#negative indexing
>>> tuple1 = (10,20,30,40,50,60,70,80)
>>> tuple1[-6:-4]
(30, 40)
#tuple is traversed in reverse order
>>> tuple1[::-1]
(80, 70, 60, 50, 40, 30, 20, 10)
Membership Operator
The in operator checks if the element is present in the
tuple and returns True, else it returns False.
>>> tuple1 = ('Red', 'Green', 'Blue')
>>> 'Green' in tuple1
True
The not in operator returns True if the element is not
present in the tuple, else it returns False.
>>> tuple1 = ('Red','Green','Blue')
>>> 'Green' not in tuple1
False
Deleting a Tuple
>>> t=(3,5,6) >>> t=(3,5,6)
>>> t
>>> del t[1] (3, 5, 6)
Traceback (most recent call >>> del(t) # Delete the whole
Tuples
last):
>>> t
File "<pyshell#8>", line 1, in Traceback (most recent call last):
<module> File "<pyshell#6>", line 1, in
<module>
del t[1] t
TypeError: 'tuple' object NameError: name 't' is not
doesn't support item deletion defined
Comparing Tuples
For comparing operators >, <, >=, <=, the corresponding
elements of two tuples must be of comparable types, otherwise
python would give an error.
Python gives the result of non equality comparisons as soon as it
gets a result in terms of true/false from corresponding elements
comparison. It jumps to next element when the first element of
both tuples is same and so on.
a=b= ( 2, 3 )
c,d = (‘2’, ‘3’ ), (2.1, 3.5)
a==b #True
a==c #False
a>b #False
d==a #False
Unpacking Tuples
Creating a tuple from a set of values is called packing
and its reverse, i.e., creating individual values from a
tuple’s elements is called unpacking
For example,
t = ( 1, 2, ‘A’, ‘B’ )
The length of tuple is 4. Now to unpack it,
w, x, y, z = t
print(w) Output - 1
print(x) 2
print(y) ‘A’
print(z) ‘B’
Lab Exercise
Write a program to create a nested
tuple to store roll number, name and
marks of students and display the result.
Example
Sud_tub=((101,"Aman",98),(102,"Geet",95),(
103,"Sahil",87),(104,"Pawan",79))
This is a program to create a nested tuple to store
roll number, name and marks of students.
st=((101,“Irfan",98),(102,“sai",95),(103,“amy",87),(104,“
ravin",79))
print("S_No"," Roll_No"," Name"," Marks")
for i in range(0,len(st)):
print((i+1),'\t',st[i][0],'\t',st[i][1],'\t',st[i][2])
Output
S_No Roll_No Name Marks
1 101 Irfan 98
2 102 sai 95
3 103 amy 87
4 104 shaji 79
Lab Exercise
Write a program to create a nested
tuple to store roll number, name and
marks of students.
Note: The students details should be in
dynamic input
#Write a program to create a nested tuple to store roll number, name and marks of students.
tuple_Storage=()
i=1
total_stud=int(input("Enter How Many Students Details : "))
while i<=total_stud:
Stud_Rollno=int(input("Enter the Student ID : "))
Stud_Name=input("Enter the Student Name : ")
Stud_Mark=int(input("Enter the Student Mark : "))
Nested_Record=(Stud_Rollno,Stud_Name,Stud_Mark)
Lt=list(tuple_Storage) # Converting Tuple into list
Lt.append(Nested_Record)
tuple_Storage=tuple(Lt) #Converting list in to Tuple
i+=1
t_length=len(tuple_Storage)
print("-------------------------------------")
print(" STUDENTS MARK DETAILS-NMS,DPS ")
print("-------------------------------------")
print("S_No"," Roll_No","\t Name\t","\tMarks")
print("-------------------------------------")
for i in range(0,t_length):
print((i+1),'\t',tuple_Storage[i][0],'\t',tuple_Storage[i][1],'\t',tuple_Storage[i][2],'\t')
0utput
Enter How Many Students Details : 2
Enter the Student ID : 1111
Enter the Student Name : JOHAN
Enter the Student Mark : 90
Enter the Student ID : 2222
Enter the Student Name : AMAN
Enter the Student Mark : 98
-------------------------------------
STUDENTS MARK DETAILS-NMS,DPS
-------------------------------------
S_No Roll_No Name Marks
-------------------------------------
1 1111 JOHAN 90
2 2222 AMAN 98
NEXT TOPIC
Tuple Functions and Methods
TUPLE iIndex()
count() METHODS
Tuple Functions and Methods
1. len() – This method returns length of the tuple, i.e., the
count of elements in the tuple.
>>>tup = ( 1, 4, ‘as’, ‘rg’, 5 )
>>>len(tup) #5
2. max() – This method returns the element from the tuple
having maximum value.
T = ( 10, 12, 14, 28, 34 )
max(T) #34
T1 = ( ‘Karan’, ‘Zubin’, ‘Zara’, ‘Ana’ )
max(T1) # ‘Zubin’
3. min( ) – This method returns the element from the tuple having
minimum value.
T = ( 10, 12, 14, 28, 34 )
min(T) #10
T1 = ( ‘Karan’, ‘Zubin’, ‘Zara’, ‘Ana’ )
min(T1) # ‘Ana’
4. index( ) method – The index() returns the index of an existing
element of a tuple.
t1=( 3, 4, 5, 6 )
t1.index(5) #2
5. Count( ) method – It returns the count of the item that you passed
as argument.
T = ( 13, 18, 29, 34, 18 )
T.count(18) #2
6.tuple()
It Creates an empty tuple if no argument is passed.
It Creates a tuple if a sequence is passed as argument.
>>> tuple1 = tuple()
>>> tuple1
()
>>> tuple1 = tuple('aeiou') #string
>>> tuple1
('a', 'e', 'i', 'o', 'u')
>>> tuple2 = tuple([1,2,3]) #list
>>> tuple2
(1, 2, 3)
>>> tuple3 = tuple(range(5))
>>> tuple3
(0, 1, 2, 3, 4)
7.sum()
Returns sum of the elements of the tuple
>>> tuple1 = (19,12,56,18,9,87,34)
>>> sum(tuple1)
235
8.sorted()
Takes elements in the tuple and returns a new sorted list. It
should be noted that, sorted() does not make any change to
the original tuple.
>>> tuple1 = ("Rama","Heena","Raj", "Mohsin","Aditya")
>>> sorted(tuple1)
['Aditya', 'Heena', 'Mohsin', 'Raj', 'Rama’].
9. del () Example : T1=(3,2,1,6)
del T1 ( It will delete entire Tuple)
del T1(1) ( Error because your trying to modify the Tuple)
CLASSROOM ACTIVITY
Write a program to find second
largest element in the tuple
Write a program to find second
largest element in the tuple
T=(23, 45, 34, 66, 77, 67, 70)
maxvalue = max(T)
length = len(T)
secmax = 0
for a in range(length):
if secmax <T[a]<maxvalue:
secmax = T[a]
print ("second largest value is :",secmax)
CLASSROOM ACTIVITY
Write a program to input n numbers from
the user. Store these numbers in a tuple.
Print the maximum and minimum number
from this tuple.
SAMPLE OUTPUT
How many numbers you want to enter?: 5
4
6
3
4
1
The numbers in the tuple are:
(4, 6, 3, 4, 1)
The maximum number is:
6
The minimum number is:
1
Write a program to input n numbers from the user. Store these numbers
in a tuple. Print the maximum and minimum number from this tuple .
numbers = tuple() #create an empty tuple 'numbers'
n = int(input("How many numbers you want to enter?: "))
for i in range(0,n):
num = int(input())
#it will assign numbers entered by user to tuple 'numbers'
numbers = numbers +(num,)
print('\nThe numbers in the tuple are:')
print(numbers)
print("\nThe maximum number is:")
print(max(numbers))
print("The minimum number is:")
print(min(numbers))
Advantages of Tuple
• Tuples are fined size in nature i.e. we can't
add/delete elements to/from a tuple.
• We can search any element in a tuple (index()).
• Tuples are faster than lists, because they have a
constant set of values.
• Tuples can be used as dictionary keys, because
they contain immutable values like strings,
numbers, etc.
• Example:
• my_dict = {(1,2): (12, 4), (3, 4): (13, 5), (5, 6): (14,
HOMEWORK
write a program to execute all the
Slicing Method and Build in function
available in Tuple
#write a program to execute all the Slicing Method and Build in function available in Tuple
t1=()
n=int(input("How many numbers to be Entered in the First Tuple : "))
for i in range(n):
x=int(input("Enter a number : "))
t1+=(x,)
print("-----------------------------------------")
print(" THE OUTPUT ")
print("-----------------------------------------")
print("The Given first Tuple = ",t1)
t2=(23,47,69,92,47,51)
print("The Given second Tuple = ",t2)
t1+=t2
print("After Adding first and second Tuple = ",t1)
print("t1[3:5]= ",t1[3:5])
print("t1[:5] = ",t1[:5])
print("t1[3:] = ",t1[3:])
print("t1[2:8:2] = ",t1[2:8:2])
print("t1[-5:8] = ",t1[-5:8])
print("t1[-4:-9:-1] = ",t1[-4:-9:-1])
print("t1[-4:-9:-1] = ",t1[-3::1])
print("t1[::-1] = ",t1[::-1])
print("t1[::] = ",t1[::])
print("Sorted Tuple in Ascending Order = ",sorted(t1))
print("Sorted Tuple in Decending Order =
",sorted(t1,reverse=True))
print("Maximum value is:",max(t1))
print("Minimum value is:",min(t1))
print("Index of 69 is:",t1.index(69))
print("Length of tuple is:", len(t1))
print("Count of 6 is:",t1.count(6))
print("Tuple in list form", list(t1))
CLASSROOM ACTIVITY
1) Write the output of the following:
T1=(1,(2,'a'),(3,'b','c'),(7,'d','e','f'))
print(T1[1][0])
print(7 in T1[3])
2) Write the output of the following:
T1=('a')*3
print(T1)
print(type(T1))
CLASSROOM ACTIVITY
3) Write the output of the following:
T1=(1,2,3,4,5,6,7,8)
print(T1[::2])
print(T1[::])
4) Write the output of the following:
T1=('Hockey','Cricket','Football')
print(max(T1))
print(min(T1))