Show Python tuple unpacking in assignments, nested tuples, loops and function calls.
Unpacking lets you take a sequence of values and bind them to several names in one statement.
# Simple swap
a, b = 1, 2
a, b = b, a
print(a, b) # 2 1
# Nested unpacking
first, (second, third) = 1, (2, 3)
print(first, second, third) # 1 2 3
# Unpacking in a loop
pairs = [(1, "a"), (2, "b")]
for number, letter in pairs:
print(number, letter)
# Unpacking a returned tuple
def split(value):
return value // 2, value % 2
whole, remainder = split(17)
print(whole, remainder) # 8 1
# Starred unpacking
head, *rest = [1, 2, 3, 4]
print(head, rest) # 1 [2, 3, 4]Every one of these is the same underlying operation: the right-hand side is evaluated to a sequence, and its elements are distributed to the targets on the left. The swap works because the right side is fully evaluated before any name is rebound. The nested form works because the parenthesised target is itself a pattern, so the inner tuple is unpacked in turn.
The starred form absorbs the remaining elements into a list. It always binds exactly one name, and the list it produces is always a list even when the rest is empty, so head, *rest = [1] gives rest as an empty list rather than None.
Unpacking also works on any iterable, not just tuples, which is why you can write a, b = some_generator and a, b = a_dict — the latter unpacks the keys in insertion order. And because it works in a for loop, iterating over a list of pairs is written as for key, value in pairs without any indexing.