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 single 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 really the same operation underneath. The right-hand side is worked out into a sequence, and then its elements are handed to the targets on the left. The swap works because the whole right side is worked out before any name is bound again. The nested form works because the target in brackets is itself a pattern, so the inner tuple is unpacked in turn.
The starred form collects the remaining elements into a list. It always binds exactly one name, and the list that it produces is always a list, even when there is nothing left over. So head, *rest = [1] gives you rest as an empty list and not as None.
Unpacking also works with any iterable and not only with tuples. That is why you can write a, b = some_generator, and it is why a, b = a_dict unpacks the keys of the dictionary in the order they were inserted. Because it works in a for loop as well, walking through a list of pairs is written as for key, value in pairs with no indexing at all. The previous question in this set looked at sorting, and this one shows the same clean style for taking values apart.