To start this guide, download this zip file.
Tuples
A tuple is a collection of one or more values, designated with parentheses:
student = ('Emma Johns', 22, 'political science')
In this case, the values might represent a student’s name, age, and major.
Tuples are immutable
A tuple is not mutable (changeable). In other words, it is immutable (not changeable).
Remember, we can change a list by appending something to it:
names = ['Anna', 'Angela']
names.append('Amy')
However, we cannot change a tuple. If we try:
student = ('Emma Johns', 22, 'political science')
student.append('3.92')
then we get an error:
Traceback (most recent call last):
File "/Users/zappala/Documents/cs110/tuples.py", line 8, in <module>
student.append('3.92')
AttributeError: 'tuple' object has no attribute 'append'
Unpacking
Let’s imagine we want to be able to print some information about a student. To do this, we could print the tuple directly:
student = ('Emma Johns', 22, 'political science')
print(student)
This will print:
('Emma Johns', 22, 'political science')
So just like printing a list will print it with the square brackets, printing a tuple will show the parentheses.
A much better way to do this is to unpack the tuple. Unpacking takes each of the parts of the tuple and stores them in separate variables:
name, age, major = ('Emma Johns', 22, 'political science')
print(f'{name} is {age} years old and a {major} major')
We now have three separate variables, name
, age
, and major
instead of just
student
. We can print those using a formatted string.
Returning multiple values
Tuples are particularly helpful for returning multiple values from a function.
This function sorts two values, a
and b
, returning the values in sorted
order:
def sorted_order(a, b):
"""Return a and b in ascending order"""
if a < b:
return a, b
else:
return b, a
Notice that we can often leave off the parentheses when returning values from a function.
We can call this function:
if __name__ == '__main__':
first, second = sorted_order(4, 2)
print(f'First comes {first}, then comes {second}')
And this will print:
First comes 2, then comes 4
In fact, this function will work with strings as well. We can call it as:
if __name__ == '__main__':
first, second = sorted_order('Amy', 'Angela')
print(f'First comes {first}, then comes {second}')
and this will print:
First comes Amy, then comes Angela
You can find this code in sorting.py
in the zip file above.
Here is another example:
def smallest_word(words):
"""Return the smallest word along with its length"""
smallest = None
for word in words:
if smallest is None or len(word) < len(smallest):
smallest = word
return smallest, len(smallest)
This function returns both the smallest word and the length of that word.
We can call it like this:
if __name__ == '__main__':
smallest_word, size = smallest_word(['apple', 'iron', 'cat', 'pigeon'])
print(f'The smallest word is {smallest_word} and it has length {size}.')
and this will print:
The smallest word is cat and it has length 3.
Notice how unpacking is particularly helpful when a function returns multiple values!
You can find this file in smallest.py
in the zip file above.
Tuples vs lists
It’s important to recognize that lists and tuples fill different roles.
list | tuple |
---|---|
Can add or remove items | Immutable |
Size dynamically determined as the program runs | Size fixed once it is created |
Typically stores items of the same type | Often stores items of different types |
The items are usually independent of each other | The items usually go together as a unit of information |
Typically processed with iteration | Typically processed by unpacking |
You typically want to use a list when you are working with a list of things that are all the same type and you don’t know how many items you will have until you run the program
You typically want to use a tuple when you are returning several values from a function or if you know in advance exactly how many items how will have (and this never changes)