13 Grouping values
Tuples
A tuple is a sequence of values, just like a list. However, unlike a list, the elements of a tuple can not be changed. You cannot append to a tuple, either. Once a tuple is made, it is immutable (or unchangeable). To make a tuple, you just use round brackets instead of square brackets:
= ("apple", "banana", "cherry") fruits
It may seem strange that Python has both tuples and lists. One reason is that tuples are more efficient, whereas lists are more flexible. We will not use tuples often, but you must know what they are.
You can do most of the operations on a tuple that you can also do on a list. The following exercises should be easy if you remember how to do the same thing on lists:
Exercise 13-1
Find the number of elements in the fruits
tuple using the len
function.
Exercise 13-2
Extract the second element of the fruits
tuple ("banana"
) using indexing.
Exercise 13-3
Try to change the second element of the fruits
tuple to "apple"
and see what happens. It should be something like this:
Traceback (most recent call last):
File "script.py", line 2, in <module>
fruits[3] = "apple"
TypeError: 'tuple' object does not support item assignment
You cannot change elements of a tuple because they are immutable (once made, they stay that way).
Tuple assignment
Python lets you assign a tuple of values to a tuple of variables like this:
= ("Donald", "Ivana", "Eric") father, mother, son
It does the same as the following three assignments:
= "Donald"
father = "Ivana"
mother = "Eric" son
When a tuple is made, the values are “packed” in sequence:
= ("Donald", "Ivana", "Eric") family
Using the same analogy, values can be “unpacked” using tuple assignment:
= family father, mother, son
The only requirement is that the number of variables equals the number of values in the tuple.
Once in a while, it is useful to swap the values of two variables. With conventional assignment statements, we have to use a temporary variable. For example, to swap a and b:
= a
tmp = b
a = tmp b
Exercise 13-4
Try this and read the error message:
= ("Donald", "Ivana", "Eric")
family = family father, mother
Exercise 13-5
Try this and read the error message:
= ("Donald", "Ivana", "Eric")
family = family father, mother, son, daughter
Compare to the error message in the previous exercise.
Exercise 13-6
Say you want to swap the values of two variables, a
and b
. To do that, you would need to keep one of the values in an extra variable like this:
= a
temp = b
a = temp b
Using what you have learned in this chapter, can you devise a simple and pretty way of swapping a
and b
in one statement? It may occur to you before you realize how it works, so make sure you can connect your solution to the rules of tuples and tuple assignment.