all Python 3Loopsconstruct
Unpacking in for
for loop
When iterating over a sequence of tuples (or of other iterables) you can unpack the items into several variables right in the for header.
Syntax
for x, y in iterable: ...
for a, b, c in iterable: ...
The count of target variables must exactly match the number of items in each tuple, or that iteration raises ValueError (not enough / too many values to unpack) — at runtime, not at parse time. When the tail length varies, a star helps: for first, *rest in ... collects the remainder into a list. Nested unpacking like for i, (x, y) in enumerate(...) needs the parentheses around the inner pair, otherwise Python expects three separate variables.
Examples
for x, y in [(1, 2), (3, 4), (5, 6)]:
print(x + y, end=" ") # → 3 7 11
pairs = {"a": 1, "b": 2, "c": 3}
for k, v in pairs.items():
print(f"{k}={v}", end=" ") # → a=1 b=2 c=3
for i, (x, y) in enumerate([(1, 2), (3, 4)]):
print(i, x, y) # → 0 1 2 / 1 3 4
for a, *rest in [(1, 2, 3), (4, 5, 6)]:
print(a, rest) # → 1 [2, 3] / 4 [5, 6]
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy