Loading lessons...
Unpack Tuples
Unpack Tuples
Unpacking pulls the items of a tuple straight into variables.
The basics
When you create a tuple, Python packs the values:
fruits = ("apple", "banana", "cherry")
To unpack, assign the tuple to matching variables:
(green, yellow, red) = fruits
print(green) # apple
print(yellow) # banana
print(red) # cherry
Asterisk * for extra items
If the number of variables doesn't match, use * to catch extras as a list:
fruits = ("apple", "banana", "cherry", "mango")
(green, yellow, *rest) = fruits
print(green) # apple
print(yellow) # banana
print(rest) # ['cherry', 'mango']
The asterisk can be anywhere
(green, *rest, red) = fruits
print(green) # apple
print(rest) # ['banana', 'cherry']
print(red) # mango
Unpacking works on lists too
The same trick applies to lists and any iterable.
TL;DR
(a, b, c) = tupleunpacks into variables.- Use
*to collect leftover items into a list. - The star can sit anywhere in the list of targets.
- Lists unpack the same way.