Course Code: CSD106A
Course Title: Programming in Python
Lecture No. 17 :
Tuples in Python
Delivered by: Dr. Anitha Kumari S D
1
Lecture Intended Learning Outcomes
At the end of this lecture, student will be able to
• Create tuples and access their elements
• Apply Built in functions on tuples
2
Contents
• Creating tuples, Operators on tuples, Built in functions on tuples, Tuple
assignment, Lists and tuples
3
Tuples in Python
• A tuple is a sequence of values
• The values can be of any type and they are indexed by integers
• Tuples are a lot like lists, but immutable (They cannot be changed once they are created)
• Suitable for data that should not be modified
• Tuple is a comma-separated list of values
>>> t='a','b','c','d','e‘
>>>t
Out[3]: ('a', 'b', 'c', 'd', 'e')
>>>type(t)
Out[4]: tuple
4
Tuples in Python
• Although it is not necessary, it is • A single value in parentheses is not a
tuple
common to enclose tuples in
>>> t2=('a')
parentheses
>>> type(t2)
>>> t=('a','b','c','d','e‘)
Out[7]: str
>>>t • To create a tuple with a single
Out[3]: ('a', 'b', 'c', 'd', 'e') element, include a final comma
>>>t3=('a',)
>>>type(t)
>>>type(t3)
Out[4]: tuple Out[9]: tuple
5
tuple() Built in function
• Tuple can be created using the built-in • If the argument is a sequence (string, list
function tuple() or tuple), the result is a tuple with the
• With no argument, it creates an empty elements of the sequence
tuple >>> t5=tuple('Learning') # this is a string
>>> t4=tuple() >>>t5
>>>t4
Out[13]: ('L', 'e', 'a', 'r', 'n', 'i', 'n', 'g')
Out[11]: ()
>>>type(t5)
>>>type(t)
Out[14]: tuple
Out[4]: tuple
6
Operators on Tuples
• Bracket[] operator indexes an element • The in and not in operators helps to
>>> t6=tuple('Python') verify whether a particular element is
present in a tuple or not
>>>t6[0]
>>> 'P' in t6
Out[16]: 'P‘
Out[19]: True
• The slice operator selects a range of
elements >>>3 in t6
>>> t6[2:4] Out[20]: False
Out[17]: ('t', 'h') >>>3 not in t6
Out[21]: True 7
Operators on Tuples
• Adding tuples • Multiplying tuples
>>> t7=(1,3,5,7) >>> t10=t7*2
>>> t8=(2,4,6,9) Out[26]: (1, 3, 5, 7, 1, 3, 5, 7)
>>>t11=t8*2
>>>t9=t7+t8
>>>t11
>>>t9
Out[28]: (2, 4, 6, 9, 2, 4, 6, 9)
Out[23]: (1, 3, 5, 7, 2, 4, 6, 9)
8
Built in Functions on Tuples
• len() is used to find length of a tuple • index() searches for the first
>>> t6=tuple('Python') occurrence of an element within the
tuple and return the index where it
>>>len(t6)
was found
Out[29]: 6
>>> t6.index('n')
• count() tells how many instances of
Out[31]: 5
the specified object is present in the
tuple >>>t6.index('a')
>>>t6.count('y') ValueError: tuple.index(x): x not in
Out[30]: 1 tuple
9
Tuples are immutable
• Tuples are immutable: Contents of a tuple cannot be changed after it's created.
• So the following operations are not allowed
my_tuple = (1, 2, 3)
my_tuple.append(4) # ❌ Error
my_tuple[0] = 10 # ❌ Error
del my_tuple[1] # ❌ Error
• A new tuple can be created by combining two tuples
• If a tuple contains a list, the list itself can be changed
• The tuple's structure cannot be changed, but a mutable object inside it can be
modified
10
Tuples are immutable
• Tuples are immutable: The elements of a Out[37]: ('A', 'a', 3, 'g')
tuple can not be modified >>>t12=(1,'a',3,'g')
• Trying to modify one of the elements of >>>t14=('A',)+t12[2:]
the tuple, results in an error
>>>t14
>>>t6[0]='A‘
Out[40]: ('A', 3, 'g')
TypeError: 'tuple' object does not support
>>>t12=(1,'a',3,'g')
item assignment
>>>t15=('A',)+t12[:]
• One tuple can be replaced with another
>>>t15
>>>t12=(1,'a',3,'g')
Out[44]: ('A', 1, 'a', 3, 'g')
>>>t13=('A',)+t12[1:]
>>>t13
11
Tuple assignment
• A tuple of values can be assigned to a tuple of variables
>>>x,y=2,3
• The left side is a tuple of variables; the right side is a tuple of expressions
>>> x
Out[46]: 2
>>> y
Out[47]: 3
• Each value is assigned to its respective variable
• All the expressions on the right side are evaluated before any of the assignments
12
Tuple assignment
• The number of variables on the left and the number of values on the right have to be the same
>>> a,b=4,5,6 #ValueError: too many values to unpack (expected 2)
• The right side can be any kind of sequence (string, list or tuple)
• For example, to split an email address into a user name and a domain
>>>addr = '[email protected]'
>>>uname, domain=addr.split('@')
#The return value from split is a list with two elements; the first element is assigned to uname, the
second to domain
>>>uname
Out[51]: 'anitha'
>>>domain
Out[52]: 'python.org'
13
Tuple assignment
• Tuples can be used to swap the values of two variables using a temporary variable
>>>a,b=4,5
>>>a,b=b,a
>>>a
Out[56]: 5
>>>b
• Out[57]: 4
14
Traversing a List of Tuples
• A for loop is used to traverse a list of tuples
>>>t13=(1,2,3,4) # Each time through the loop, Python selects
>>>for number in t13: the next tuple in the list and assigns the
print(number) elements to the variable number
Out
1
2
3
4
>>>t14=(1,2,3,4)
>>>for number in t14:
print(number,end=' ')
Out: 1 2 3 4
15
Comparing Tuples
• The relational operators work with tuples
• Python starts by comparing the first element from each sequence
• If they are equal, it goes on to the next elements, and so on, until it finds elements that differ
>>>(0,1,2)<(0,3,4)
Out[60]: True
• Subsequent elements are not considered (even if they are really big)
>>>(0,1,2000000) < (0, 3, 4)
Out[61]: True
• Comparing two tuples to determine if they are equal or not is done by == or != operators
16
Comparing Tuples
• Comparing two tuples to determine if • Comparing two tuples to determine if
they are equal or not is done by == or they are equal or not is done by == or
!= operators != operators
>>>tuple1 = (1,2,3) >>>tuple1 = (1,2,3)
>>>tuple2 = (1,2,3) >>>tuple2 = (1,2,0)
>>>if tuple1==tuple2 : >>>if tuple1==tuple2 :
print('Both tuples are equal') print('Both tuples are equal')
>>>else: >>>else:
print ('Tuples are different') print ('Tuples are different')
Out: Both tuples are equal Out: Tuples are different
17
List and Tuples
• zip is a built-in function that takes two or more sequences and “zips” them where each
list/tuple contains one element from each sequence
>>>mylist=['India', 'China','Russia'] # list
>>>mycap=['Delhi', 'Beijing','Moscow'] # list
>>>list_cap=list(zip(mylist,mycap))
>>>list_cap
Out[3]: [('India', 'Delhi'), ('China', 'Beijing'), ('Russia', 'Moscow')]
>>>type(list_cap)
Out[5]: list
The result contains a character from mylist and the corresponding element from the list
mycap
18
List and Tuples
mylist1=['Karnataka', 'Kerala', 'TamilNadu'] # list
mycap1=['Bengaluru', 'Trivandrum', 'Chennai'] # list
list_cap1=tuple(zip(mylist1,mycap1))
list_cap1
Out[2]: (('Karnataka', 'Bengaluru'),
('Kerala', 'Trivandrum'),
('TamilNadu', 'Chennai'))
>>>type(list_cap1)
Out[3]: tuple
19
List and Tuples
>>>mylist2=('India', 'China', 'Russia') # tuple
>>>mycap2=('Delhi', 'Beijing', 'Moscow') # tuple
>>>list_cap2=list(zip(mylist2,mycap2))
>>>list_cap2
Out[3]: [('India', 'Delhi'), ('China', 'Beijing'), ('Russia', 'Moscow')]
>>>type(list_cap2)
Out[5]: list
20
List and Tuples
>>>mylist3=('India', 'China', 'Russia')
>>>mycap3=('Delhi', 'Beijing','Moscow')
>>>list_cap3=tuple(zip(mylist3,mycap3))
>>>list_cap3
Out[9]: (('India', 'Delhi'), ('China', 'Beijing'), ('Russia', 'Moscow'))
>>>type(list_cap3)
Out[10]: tuple
21
List and Tuples
• If the sequences are not the same length, the result has the length of the shorter
one
>>>list(zip('Civil','Automotive'))
Out[3]: [('C', 'A'), ('i', 'u'), ('v', 't'), ('i', 'o'), ('l', 'm')]
>>>tuple(zip('Civil','Automotive'))
Out[4]: (('C', 'A'), ('i', 'u'), ('v', 't'), ('i', 'o'), ('l', 'm'))
22
List vs Tuples
• What type of data goes into a tuple? (Fixed or changeable?)
• What type of data goes into a list?
• Can you sort a tuple?
• Which one uses more memory?
• Try storing a list inside a tuple
trip = ("Paris", ["passport", "ticket", "map"])
trip[1].append("umbrella")
print(trip)
23
List vs Tuples
• Simple, real-world situation where a tuple is better than a list
• Storing GPS Coordinates: latitude and longitude of a location
# Tuple: (latitude, longitude)
location = (28.6139, 77.2090)
# List: [latitude, longitude]
location = [28.6139, 77.2090]
location[0] = 0 # 😬 Oops! You just changed the location!
24
Program using Tuple
# program to generate the first ‘n’ Fibonacci terms
>>>t1=t2=1
>>>n =int(input("How many terms? "))
>>>for i in range(n):
print(t1)
t1,t2 = t2,t1+t2
How many terms?4
1
1
2
3
25
Group Activity
You are planning a trip with friends! You'll use tuples for information that should not change (like
your destination or dates), and lists for things you might update (like your packing list or sightseeing
spots).
26
Summary
• A tuple is an immutable sequence of elements
• Elements of a tuple can be accessed using []
• The len() gives the number of elements in a tuple
• The for loop can be used to iterate through the elements of a tuple
• A tuple slice is an independent tuple made up of elements taken from a tuple
using the [:] syntax
27