Python Reference ยท Lists, Tuples and Ranges
Python unpacking and star expressions
Reference for Python unpacking: assign items to several names, collect the rest with a star, swap values, unpack in calls and literals with * and **.
Unpacking assigns the items of an iterable to several names in one statement. first, second = [10, 20] gives first the value 10 and second the value 20. Any iterable works: lists, tuples, strings, dictionaries, generators and ranges.
A star expression adds flexibility. A starred name collects "the rest" into a list when assigning, and a starred argument or element spreads an iterable out when calling a function or building a list, tuple, set or dict.
head, *tail = [1, 2, 3, 4] print(head, tail) # 1 [2, 3, 4]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
How unpacking works
Basic unpacking
The number of names on the left must match the number of items produced by the right side, otherwise Python raises ValueError ("too many values" or "not enough values"). The right side is evaluated completely first, which is why a, b = b, a swaps values safely: it builds a tuple and then unpacks it.
Unpacking nests: (p, q), r = (1, 2), 3 matches the structure on both sides. It is also used in for loops, with ... as (a, b), comprehensions and function return values.
Star in assignment
At most one name in a target list may carry a star. It receives all items not matched by the other names, and it is always a list, even when the source is a tuple or string. It can be empty. first, *middle, last = [1, 2] makes middle an empty list.
Star in calls and literals
In a call, *iterable passes its items as separate positional arguments, and **mapping passes key-value pairs as keyword arguments. In list, tuple and set displays, * splices an iterable in place. In a dict display, ** splices another mapping, and later keys override earlier ones. Several of these can appear in one expression.
Unpacking dictionaries
Unpacking a dict directly gives its keys. Use .items() for pairs, as in the loop above.
Usage notes
- Use
_for values you ignore by convention. It is a normal name, but it signals intent._can appear several times. - Starred names are lists, so
*restfrom a tuple is not a tuple. Wrap intuple()if you need one. - Only one starred target is allowed per level of the target list; two are a
SyntaxError. - Infinite iterators hang with a starred target, because Python tries to collect everything.
- Strings unpack into characters, which surprises people:
a, b = "hi"works,a, b = "hey"fails. - Sets and dicts unpack in their iteration order. For sets, that order is arbitrary, so sort first.
**in calls requires string keys and raisesTypeErrorif an argument is given twice.- Dict merging with
{**a, **b}produces a new dict; the originals are not changed. Since Python 3.9 the|operator does the same.