Lecture 33 – Python Tuples-I
Programming Fundamentals
Learning Outcomes
• After studying this lecture, students will be able to:
• Identify when to use a tuple.
• Explain how Python uses tuple to store multiple data values.
• Create new Python tuple that contain int, float and str values.
• Use the tuple index to access items from a Python tuple.
• Perform tuple operations
• Use the most common tuple functions and methods
• Know how to create nested tuples
Outline
• Introduction to Tuples
• Creating a Tuple
• Tuple Assignment
• Accessing Elements using Indexing and Slicing
• Negative Indexing
• Iterating over the elements in a Tuple
• Updating Tuple Elements
• Memory Concept
• Deleting Tuple Elements
Introduction to Tuples
• Tuples are sequences, just like lists. The values stored in a tuple can be any type,
and they are indexed by integers.
• Tuple is similar to lists since the value of the items stored in the list can be
changed whereas the tuple is immutable and the value of the items stored in the
tuple can not be changed.
Creating a Tuple
• When you create a tuple, you enclose its elements in a set of parentheses, separated by
commas, as shown below:
>>my_tuple = (1, 2, 3, 4, 5)
>>print(my_tuple)
(1, 2, 3, 4, 5)
• The first statement creates a tuple containing the elements 1, 2, 3, 4, and 5 and assigns it to the
variable my_tuple. The second statement sends my_tuple as an argument to the print function,
which displays its elements.
• The empty tuple is written as two parentheses containing nothing.
>> tup1 = ()
• To write a tuple containing a single value you have to include a comma, even though there is
only one value.
>> tup1 = (50,)
Tuple Packing & Unpacking
• A tuple can also be created without using parentheses. This is known as tuple packing. When a
tuple is created, the items in the tuple are packed together into the object.
>>T = ('red', 'green', 'blue', 'cyan’)
>> print(T)
• In above example, the values ‘red’, ‘green’, ‘blue’ and ‘cyan’ are packed together in a tuple.
Tuple Packing & Unpacking
• When a packed tuple is assigned to a new tuple, the individual items are unpacked (assigned to the items of a new
tuple).
>> T = ('red', 'green', 'blue', 'cyan’)
>> (a, b, c, d) = T
>> print(a)
>> print(b)
>> print(c)
>>print(d)
red
green
blue
cyan
• In above example, the tuple T is unpacked into a, b, c and d variables.
• The left side is a tuple of variables; the right side is a tuple of expressions. Each value is assigned to its respective
variable.
Tuple Packing & Unpacking
• When unpacking, the number of variables on the left must match the number of items in the tuple.
>> T = ('red', 'green', 'blue', 'cyan’)
>> (a, b) = T
Triggers ValueError: too many values to unpack
>> T = ('red', 'green', 'blue’)
>> (a, b, c, d) = T
Triggers ValueError: not enough values to unpack (expected 4, got 3)
• While unpacking a tuple, the right side can be any kind of sequence (tuple, string or list).
>> addr = '
[email protected]’
>> user, domain = addr.split('@’)
>> print(user)
>> print(domain)
bob
python.org
Accessing Elements using Indexing and
Slicing
• We can use the index operator [] to access an item in a tuple where the index starts from 0. So, a
tuple having 6 elements will have indices from 0 to 5.
• We can access a range of items in a tuple by using the slicing operator - colon ":".
>>tup1 = ('physics', 'chemistry', 1997, 2000)
>>tup2 = (1, 2, 3, 4, 5, 6, 7 )
>>print ("tup1[0]: ", tup1[0])
>>print ("tup2[1:5]: ", tup2[1:5])
tup1[0]: physics
tup2[1:5]: (2, 3, 4, 5)
• Trying to access an element outside of tuple (for example, 6, 7,...) will raise an IndexError.
Negative Indexing
• Python allows negative indexing for its sequences.
• The index of -1 refers to the last item, -2 to the second last item and so on.
• Example:
>>thistuple =
("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"
)
>>print(thistuple[-1])
>>print(thistuple[-4:-1])
mango
('orange', 'kiwi', 'melon')
Iterating over the elements in a
Tuple
• You can loop through the tuple items by using a for loop.
>>names = ('Holly', 'Warren’)
>>for n in names:
print(n)
Holly
Warren
• Like lists, tuples support range() method to iterate over a tuple in Python.
>>names = ('Holly', 'Warren’)
>>for i in range(len(names)):
print(names[i])
Holly
Warren
Updating Tuple Elements
• Once a tuple is created, you cannot change its values. Tuples are unchangeable,
or immutable as it also is called.
• But there is a workaround. You can convert the tuple into a list, change the list,
and convert the list back into a tuple. For Example:
>>x = ("apple", "banana", "cherry")
>>y = list(x)
>>y[1] = "kiwi"
>>x = tuple(y)
>>print(x)
("apple", "kiwi", "cherry“)
Updating Tuple Elements
• Or you can replace one tuple with another. For Example:
>>t = ('a', 'b', 'c', 'd', 'e’)
>>t = ('A',) + t[1:]
>>print(t)
('A', 'b', 'c', 'd', 'e')
• We can also assign a tuple to different values (reassignment).
>>a = ("apple", "banana", "cherry")
>>a = ("apple", "kiwi", "cherry“)
• Are we actually modifying the first item in tuple a with the code above?
• The answer is No, absolutely not. Why?
Updating Tuple Elements – Memory Concept
• Let’s see what happens if we perform the reassignment on tuples.
a = ("apples", "bananas", "oranges")
id(a)
>> 4340765824
a = ("berries", "bananas", "oranges")
id(a)
>> 4340765464
• As you can see, the two addresses are different.
• This means that after the second assignment, a is referring to an entirely new
object.
Updating Tuple Elements – Memory Concept
• This figure shows exactly what happened.
• Moreover, if no other variables in your program is referring to the older tuple then python’s
garbage collector will delete the older tuple from the memory completely.
• So there you have it, this concept of mutability is the key difference between lists and tuples.
Deleting Tuple Elements
• Removing individual tuple elements is not possible. There is, of course, nothing
wrong with putting together 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)
>>print tup
>>del tup
References
• Think Python: How to Think like a Computer Scientist by Allen B. Downey, Publisher: O'Reilly
Media; 2 edition (December 28, 2015).
• Starting Out with Python by Tony Gaddis, Pearson; 4 edition (March 16, 2017)
• https://www.programiz.com/python-programming/tuple
• https://www.tutorialspoint.com/python/python_tuples.htm