Sub topic 9
Unpacking Nested Structures
What this chapter assumes
You should already know how tuples are created and how basic unpacking works: x, y = 3, 4, swaps, and starred targets such as first, *rest = items. You also need for loops and function definitions. This chapter extends those ideas to values that contain other sequences.
The core idea: mirror the shape
Plain unpacking matches one flat sequence to a flat list of names. Nested unpacking lets the target on the left mirror the nesting of the value on the right. Where the value holds an inner sequence, you write an inner group of names in parentheses.
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 left side is also two targets: the name name, and a group (lat, lon). Python unpacks the outer tuple first. It then unpacks the second item into lat and lon. The output is Oslo 59.91 10.75.
Read each level of the pattern against the same level of the value. The names at the leaves of the pattern are the only things that get bound. The parentheses on the left are not tuple creation. In a target position they only say "unpack this item further".
Any iterable works at every level
The inner group can be matched against any iterable, not only a tuple. Square brackets on the left are also allowed and mean the same thing as parentheses.
record = ("Ada", (1815, 12, 10), ["math", "poetry"])
name, (year, month, day), (field1, field2) = record
print(name, year, month, day, field1, field2)
[a, b], c = (1, 2), 3
print(a, b, c)The first print shows Ada 1815 12 10 math poetry. The record mixes a tuple and a list, and the pattern does not care which is which. Only the lengths have to agree. The second print shows 1 2 3.
You can nest more than two levels deep, and a group may sit at the start of the pattern:
segment = ((0, 0), (4, 3))
(x1, y1), (x2, y2) = segment
print(x2 - x1, y2 - y1)This prints 4 3. Two groups of two names replace four index expressions such as segment[1][0]. That is the main payoff: you name the parts once, at the point where you take the value apart, and the later code reads clearly.
Ignoring parts you do not need
When you must match a position but do not need its value, use _ as a throwaway name by convention.
city, (lat, _) = "Oslo", (59.91, 10.75)
print(city, lat)This prints Oslo 59.91. The underscore is an ordinary variable name that Python binds like any other. Nothing special happens, so a later _ overwrites the earlier one. Do not rely on its value. If you need to skip a whole variable-length section, combine it with a star, as in first, *_ = items.
Combining nesting with starred targets
A starred target can appear inside an inner group as well as in the outer pattern. The rule is that each group allows at most one starred target. The outer pattern and each inner group count separately.
label, (first, *others) = "team", (1, 2, 3, 4)
print(label, first, others)
a, (b, *c), *d = 1, (2, 3, 4), 5, 6
print(a, b, c, d)The first print shows team 1 [2, 3, 4]. The second shows 1 2 [3, 4] [5, 6]. A starred name always receives a list, even when the source was a tuple, and it receives an empty list when nothing is left over.
Nested targets in loops and comprehensions
A for target accepts the same nested patterns. This is common when each item of a list is itself a pair that contains a pair.
cities = [("Oslo", (59.91, 10.75)), ("Lima", (-12.05, -77.04))]
for city, (lat, lon) in cities:
print(f"{city}: {lat}, {lon}")
ranges = {"temp": (10, 30), "humidity": (40, 80)}
for key, (low, high) in ranges.items():
print(key, high - low)The first loop prints Oslo: 59.91, 10.75 and Lima: -12.05, -77.04. The second prints temp 20 and humidity 40. The dict.items() call yields (key, value) pairs, and the value here is itself a pair, so the target is key, (low, high). The same target syntax works after for inside a comprehension, for example [lat for _, (lat, _) in cities].
Function parameters do not unpack
In Python 2 you could write def f(a, (b, c)):. Python 3 removed this (PEP 3113). The same is true of lambda (a, b): .... Both are a SyntaxError today. Take one parameter and unpack it on the first line of the body instead:
def describe(entry):
city, (lat, lon) = entry
return f"{city} at {lat}, {lon}"
print(describe(("Oslo", (59.91, 10.75))))This prints Oslo at 59.91, 10.75. For a key= function you can usually index instead, as in lambda c: c[1][0], or write a small def.
Nested returns
A function that returns a tuple of tuples can be unpacked by the caller in one statement. The returned shape becomes part of the function's contract, so document it.
def bounding_box(points):
xs = [x for x, _ in points]
ys = [y for _, y in points]
return (min(xs), min(ys)), (max(xs), max(ys))
(left, bottom), (right, top) = bounding_box([(1, 5), (4, 2), (3, 9)])
print(left, bottom, right, top)This prints 1 2 4 9. Note that the comprehensions use the same flat unpacking from earlier chapters on each point. The nesting appears only in the return value.
What the pattern can and cannot check
The pattern checks only lengths and whether an item is iterable. It does not check types or values. The table shows what happens for the pattern name, (lat, lon).
| Right-hand side | Result |
|---|---|
| `"Oslo", (59.91, 10.75)` | Works. |
| `"Oslo", [59.91, 10.75]` | Works. A list is fine in the inner position. |
| `"Oslo", (59.91, 10.75, 0)` | ValueError: too many values to unpack (expected 2). |
| `"Oslo", 5` | TypeError: cannot unpack non-iterable int object. |
| `"Oslo", "hi"` | Works silently: `lat` is `"h"`, `lon` is `"i"`. |
You can see all three failure modes with a small test:
cases = [
("Oslo", (59.91, 10.75, 0)),
("Oslo", 5),
("Oslo", "hi"),
]
for case in cases:
try:
name, (lat, lon) = case
print("ok", name, lat, lon)
except (ValueError, TypeError) as e:
print(type(e).__name__, e)The output is:
ValueError too many values to unpack (expected 2)
TypeError cannot unpack non-iterable int object
ok Oslo h iThe third case is the dangerous one. A string is an iterable of characters, so a two-character string fits a two-name group. The code runs without complaint and gives wrong data. If an inner value might be a string when you expect a pair, validate it before unpacking.
Pitfalls to watch for
- Partial assignment. Python assigns targets from left to right. If an inner group fails, the names to its left are already bound.
try:
a, (b, c) = 1, (2, 3, 4)
except ValueError as e:
print(e)
print(a)This prints too many values to unpack (expected 2) and then 1. The error was raised while unpacking the inner group, but a had been assigned first. Do not assume a failed unpacking leaves your names untouched.
- Error messages do not say which level failed. The message "expected 2" refers to whichever group had the wrong length. With deep patterns, check the shape of the data in a debugger or with
print(repr(value)). - Inner names are ordinary variables. They leak into the surrounding scope just like any assignment. In a comprehension they stay local to it.
- Deep patterns age badly. Three levels of nesting on one line is hard to read and breaks whenever the data shape changes. If a record has more than a few fields, a named tuple or dataclass with names is clearer than a position-based pattern.
Summary of the rules
- The left side mirrors the nesting of the right side. Parentheses or brackets in a target mean "unpack this item further".
- Any iterable can be matched at any level, including lists, strings, ranges and generators. Length is the only structural check.
- Each group, outer or inner, can have one starred target, which collects a list.
- The same patterns work in
fortargets and comprehensions, but not in Python 3 function or lambda parameters. - Targets are bound left to right, so a failure can leave earlier names assigned.
Exercise
Given data = ("trip", [("Oslo", 3), ("Bergen", 2), ("Tromso", 4)]), write one assignment that binds title to the first item, first_city and first_days to the first pair of the list, and remaining to a list of the other pairs.
Show answer
title, [(first_city, first_days), *remaining] = data. After it runs, title is "trip", first_city is "Oslo", first_days is 3, and remaining is [("Bergen", 2), ("Tromso", 4)]. The star sits inside the inner list pattern, which is allowed because each group may have one starred target.
Exercise
What happens when you run name, (lat, lon) = "Oslo", "hi", and why is that a risk? Name one way to guard against it.
Show answer
It runs without an error and binds lat to "h" and lon to "i". A string is an iterable of characters, and a two-character string matches a two-name group. The risk is silently wrong data. To guard against it, check the type before unpacking, for example isinstance(coords, tuple), or convert and validate the value first.
Exercise
A learner writes key=lambda (name, score): score to sort pairs by score and gets a SyntaxError. Why, and how do you fix it?
Show answer
Python 3 removed tuple parameter unpacking (PEP 3113), so parameters cannot contain unpacking patterns. Use a single parameter and index it: key=lambda pair: pair[1]. Alternatively, write a def that unpacks on its first line, name, score = pair, and then returns score.