PythonLists and tuples
Unpacking sequences
Assigning the items of a tuple or list to several variables at once.
- Returns
- Nothing; this is an assignment.
Example
#Python
name, level = ("Emma", 7)
print(name, level)
first, *middle, last = [10, 20, 30, 40, 50]
print(first, middle, last)
a, b = 1, 2
a, b = b, a
print(a, b)Resultsaved result, you can check it
Emma 7
10 [20, 30, 40] 50
2 1
Definition and usage
#Unpacking lets you assign the items of a sequence to several variables in a single statement: x, y = (3, 4). The number of variables must match the number of items.
A starred variable collects the "rest": first, *rest = [1, 2, 3, 4] gives first = 1 and rest = [2, 3, 4]. The star can appear in any position, but only once.
Thanks to unpacking, swapping the values of two variables is a, b = b, a, and functions can conveniently return several values. In loops, you unpack pairs from enumerate(), zip(), and dict.items().
Syntax
#Syntax
a, b = sequence
first, *rest = sequenceMore examples
#Python
try:
x, y, z = [1, 2]
except ValueError as error:
print(error)Resultsaved result, you can check it
not enough values to unpack (expected 3, got 2)
Good practices
#- Assign values you do not need to
_:name, _ = pair. - Unpacking in a
for key, value in d.items():loop is more readable than accessing items by index.
Related entries
#Spotted a mistake or missing an example? Write to us.