Sub topic 3
Unpacking Nested Structures
Assume you know Python variables, lists, indexing, functions, and for loops. Unpacking assigns items from an iterable to several names at once. The target pattern can match nested structure.
Unpacking nested structures
name, (latitude, longitude) = "Oslo", (59.91, 10.75)
print(name, latitude, longitude)The outer value has two items. Its second item is another tuple, so (latitude, longitude) unpacks that inner tuple.
You can use the same pattern with lists and other iterables:
record = ["Ada", [1815, 12, 10]]
name, (year, month, day) = record
print(name, year, month, day)Unpacking in loops
Loop targets can unpack each item as it is produced. This is useful with enumerate, zip, and dictionary items().
names = ["Ada", "Linus", "Grace"]
scores = [95, 88, 91]
for number, (name, score) in enumerate(zip(names, scores), start=1):
print(number, name, score)
prices = {"apple": 1.20, "pear": 0.80}
for item, price in prices.items():
print(item, price)zip pairs values, enumerate adds a counter, and items() produces key-value pairs.
Returning values and unpacking arguments
A function that returns several comma-separated values returns one tuple.
def min_max(values):
return min(values), max(values)
low, high = min_max([3, 1, 4, 1, 5])
print(low, high)
arguments = (2, 10)
print(pow(*arguments))The * in pow(*arguments) spreads the tuple into positional arguments.
Named tuples for readable records
A named tuple keeps tuple behavior while adding named fields.
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
point = Point(3, 4)
x, y = point
print(point.x, point.y)Use a plain tuple for a small, obvious grouping. Use a named tuple when field names improve readability. For records that must change, use a class or a dataclass instead.
Common errors and pitfalls
The number of targets must match the number of values unless a starred target collects the remainder.
first, *middle, last = [10, 20, 30, 40]
print(first, middle, last)A mismatch raises ValueError. A nested pattern also fails if the inner value has the wrong shape.
Exercise
What exception does a, b = (1, 2, 3) raise?
Show answer
ValueError, because there are three values but only two targets.