Sub topic 6
Packing and unpacking
This chapter assumes you know basic Python syntax, lists and indexing, how to define and call functions, and how for loops work. It also assumes you can already create a tuple, including the one-element form (3,).
The working model
Packing builds a tuple from several values. Unpacking does the reverse: it assigns the items of an iterable to separate names in one statement.
The comma makes the tuple, so no parentheses are needed on the right-hand side. The left-hand side of an unpacking assignment is a target list. Python evaluates the right side first, then assigns its items to the targets from left to right.
point = 3, 4 # packing: a tuple (3, 4)
x, y = point # unpacking: x is 3, y is 4
print(point, x, y)
a, b, c = "abc" # any iterable works, including a string
print(a, b, c)
p, q = [10, 20] # a list works too
print(p, q)The right side does not have to be a tuple. Strings, lists, ranges, dictionaries, generators and any other iterable all work. Python consumes the iterable and counts the items it produces.
Multiple assignment and swapping
Because the right side is fully evaluated before any name is assigned, you can swap two values without a temporary variable.
x, y = 3, 4
x, y = y, x
print(x, y)Here Python packs (y, x) as (4, 3), then assigns x = 4 and y = 3. The same idea lets you rotate or reorder several names at once, for example a, b, c = c, a, b.
Starred targets
A target with * collects the items that the other targets did not take. It always receives a list, even when it receives nothing.
first, *rest = [1, 2, 3, 4]
print(first, rest)
head, *middle, last = range(5)
print(head, middle, last)
one, *others = [7]
print(one, others)The last call prints 7 []. Only one starred target is allowed per target list. The starred name takes whatever remains after the plain targets are filled, so the plain targets decide how many items must exist at minimum.
Nested unpacking
The target pattern can mirror the shape of the value. An inner tuple on the left unpacks an inner sequence on the right.
name, (lat, lon) = "Oslo", (59.91, 10.75)
print(name, lat, lon)The inner pattern follows the same rules as the outer one. The inner sequence must have exactly two items here, or Python raises an error.
Common errors
Unpacking checks lengths at run time. Without a starred target, the number of targets must equal the number of items.
try:
a, b = (1, 2, 3)
except ValueError as e:
print(e)
try:
a, b, c = (1, 2)
except ValueError as e:
print(e)The first message is too many values to unpack (expected 2). The second is not enough values to unpack (expected 3, got 2).
| Situation | Result |
|---|---|
| More items than targets, no star | `ValueError: too many values to unpack` |
| Fewer items than targets | `ValueError: not enough values to unpack` |
| Star target and enough items | Star target gets a list, possibly empty |
| Right side is not iterable, such as `a, b = 5` | `TypeError: cannot unpack non-iterable int object` |
Where this leads
The same unpacking rules apply in for loop targets, in function return values, and in * argument spreading. The following chapters cover each of those uses.
Exercise
Given data = ["id7", "a", "b", "c", 42], write one unpacking statement that puts "id7" in ident, 42 in value, and the three letters in a list called letters. Then say what happens if data is ["id7", 42].
Show answer
ident, *letters, value = data. This gives ident = "id7", letters = ["a", "b", "c"] and value = 42. With ["id7", 42], letters becomes an empty list [], and no error is raised, because the two plain targets are satisfied. With a one-item list, it would raise ValueError: not enough values to unpack (expected at least 2, got 1).
Exercise
What do x and y hold after x, y = 1, 2 followed by x, y = y, x + y?
Show answer
x is 2 and y is 3. The right side (y, x + y) is evaluated first using the old values, giving (2, 3), and only then are the names assigned.