Sub topic 3
Tuples: fixed records and unpacking
This chapter assumes you know basic Python syntax, the built-in types int, str, and bool, and how to run Python 3 in a REPL or script. It also assumes you have met lists, which the previous chapter covered. A tuple is an ordered sequence like a list, but it cannot be changed after you create it.
What a tuple is
A tuple is an ordered, immutable sequence. Immutable means you cannot add, remove, or replace its items. You usually write one with parentheses and commas.
point = (3, 4)
print(point[0]) # 3
print(len(point)) # 2
print(point[-1]) # 4
try:
point[0] = 1
except TypeError as e:
print(e) # 'tuple' object does not support item assignmentIndexing, slicing, len, in, and iteration all work as they do for lists. Only the operations that change the sequence are missing. A tuple has no append, remove, sort, or item assignment.
The comma makes the tuple
The comma creates a tuple, not the parentheses. This matters for a tuple with one item.
a = (5) # just the int 5
b = (5,) # a tuple with one item
c = 5, 6 # a tuple, parentheses are optional here
empty = () # the empty tuple
print(type(a).__name__) # int
print(type(b).__name__) # tuple
print(type(c).__name__) # tuple
print(len(empty)) # 0A missing trailing comma in a one-item tuple is a common source of bugs. (5) is only the number 5 in grouping parentheses.
Tuples as fixed records
Use a tuple when the position of each item has a meaning and the number of items is fixed. A point (x, y), an RGB color (red, green, blue), or a database row (id, name, age) are typical records. A list usually holds many items of the same kind. A tuple usually holds a few items of different kinds.
person = ("Ana", 31, "Lisbon")
name = person[0]
print(name) # AnaIndex numbers such as person[0] are easy to forget. Unpacking, shown next, removes most of them.
Unpacking
Unpacking assigns the items of a tuple to several names in one statement. The number of names must match the number of items.
person = ("Ana", 31, "Lisbon")
name, age, city = person
print(name, age, city) # Ana 31 Lisbon
# Swapping two variables without a temporary
x, y = 1, 2
x, y = y, x
print(x, y) # 2 1The swap works because the right side is evaluated into a tuple (y, x) first. Then the names are assigned.
A mismatch raises ValueError.
try:
a, b = (1, 2, 3)
except ValueError as e:
print(e) # too many values to unpack (expected 2)Starred unpacking
A name with a * in front collects the leftover items into a list. Only one starred name is allowed per assignment.
first, *middle, last = (10, 20, 30, 40, 50)
print(first) # 10
print(middle) # [20, 30, 40]
print(last) # 50Note that middle is a list, even though the source is a tuple.
Unpacking in loops and returns
Functions that return several values are really returning one tuple. Loops can unpack each item as they go.
def min_max(values):
return min(values), max(values) # one tuple
low, high = min_max([4, 9, 2, 7])
print(low, high) # 2 9
pairs = [("ana", 31), ("ben", 27)]
for name, age in pairs:
print(f"{name} is {age}")
for index, letter in enumerate("abc"):
print(index, letter)The enumerate function and dict.items() both yield tuples, so you will unpack constantly.
How a tuple differs from a list
The table summarizes the differences you will use most.
| Feature | list | tuple |
|---|---|---|
| Syntax | `[1, 2]` | `(1, 2)` or `1, 2` |
| Change items in place | Yes | No |
| Typical use | Many similar items | Fixed record of a few items |
| Can be a dict key | No | Yes, if all items are hashable |
The last row depends on hashability, which the next chapter covers. A tuple of numbers or strings can be a dict key. A list never can.
Immutable, but only one level deep
Immutability applies to the tuple's own slots. Each slot always refers to the same object. If that object is mutable, such as a list, the object can still change.
t = (1, [2, 3])
t[1].append(4)
print(t) # (1, [2, 3, 4])The tuple still holds the same list in slot 1. The list itself grew. Later chapters return to this under common pitfalls.
Where tuples fit
Exercises
Exercise
What does type((7)) return, and how do you write a tuple holding only the number 7?
Show answer
type((7)) returns int, because the parentheses only group the number. A one-item tuple needs a trailing comma: (7,) or 7,.
Exercise
Given data = (1, 2, 3, 4, 5), write one line that puts 1 in head and the remaining items in tail. What type is tail?
Show answer
head, *tail = data. The value of tail is [2, 3, 4, 5], which is a list.
Exercise
After t = ("a", ["x"]) and t[1].append("y"), what does t contain, and why is no error raised?
Show answer
t is ("a", ["x", "y"]). The code never assigns to a tuple slot. It changes the list that the slot refers to, and the list is mutable.