Sub topic 9
Unpacking nested structures
This chapter assumes you know basic packing and unpacking (x, y = 3, 4), starred targets (first, *rest = items), and how a for loop assigns its loop variable. Here you apply those ideas to data that contains other data.
Mirroring the shape of the value
The target on the left of = can have the same nesting as the value on the right. Python matches the two structures position by position. An inner tuple or list in the target unpacks the matching inner item.
name, (lat, lon) = "Oslo", (59.91, 10.75)
print(name, lat, lon)The right side is a tuple of two items: a string and a pair. The target name, (lat, lon) has two slots, and the second slot unpacks the pair. Inner parentheses in the target are required. Without them, name, lat, lon would expect three items and raise ValueError.
city = ("Oslo", (59.91, 10.75), ["museum", "park", "harbour"])
name, (lat, lon), (first_tag, *other_tags) = city
print(name, lat, lon)
print(first_tag, other_tags)This prints Oslo 59.91 10.75 and then museum ['park', 'harbour']. The inner pattern can be written with parentheses or square brackets, and it works on lists, tuples, strings, or any other iterable. Starred targets work at any level, but each level may have only one.
Nested targets in loops
A for target is an ordinary assignment target, so it can be nested too. This is the usual way to handle records that hold a smaller group inside.
trips = [
("Ada", (0, 0), (3, 4)),
("Linus", (1, 1), (4, 5)),
]
for name, (x1, y1), (x2, y2) in trips:
distance = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
print(name, distance)Each record unpacks into a name and two coordinate pairs. This prints Ada 5.0 and Linus 5.0.
The same idea applies to enumerate over zip. The pair from zip sits inside the pair from enumerate, so the target needs parentheses around the inner names:
names = ["Ada", "Linus"]
scores = [95, 88]
for i, (name, score) in enumerate(zip(names, scores), start=1):
print(i, name, score)Common errors with nested targets
The shape of the value must match the shape of the target. When it does not, Python raises one of two errors.
try:
name, (lat, lon) = "Oslo", 59.91
except TypeError as e:
print(e)
try:
name, (lat, lon) = "Oslo", (59.91, 10.75, 5)
except ValueError as e:
print(e)The first case fails because a float is not iterable, so it cannot fill the inner pair. The message is cannot unpack non-iterable float object. The second case fails because the inner pair has three items for two names. The message is too many values to unpack (expected 2).
A string is iterable, so it can fill an inner pattern without any error:
name, (a, b) = "Oslo", "hi"
print(a, b)This prints h i. The code runs, but it is almost certainly not what you meant. When data comes from outside your program, check its shape first, or catch the error where you unpack it.
When nesting stops helping
Deep patterns such as (a, (b, (c, d))) are legal, but they are hard to read and hard to debug when the shape changes. As a rough guide:
| Situation | Better choice |
|---|---|
| One level of nesting, fixed shape | Nested unpacking |
| Two or more levels, or many fields | A named tuple, dataclass, or dict |
| Shape varies between records | Index or inspect explicitly, then unpack |
Exercise
Given record = ("Grace", [91, 85, 77]), write one assignment that binds name to the string, best to the first score, and others to a list of the remaining scores. What are the three values?
Show answer
name, (best, *others) = record. The values are name = "Grace", best = 91 and others = [85, 77]. The inner pattern unpacks the list, and the starred target collects the leftover scores into a list.
Exercise
What error does a, (b, c) = 1, 2 raise, and why?
Show answer
TypeError: cannot unpack non-iterable int object. The target expects the second item to be an iterable that it can split into two names, but the value is the integer 2.