Search notes:

Python: Iterable unpacking

Iterable unpacking allows to assign the elements of an iterable to multiple variables.
This technique is often used for «shift» like operations (as is for example known from the Perl function shift.
>>> print(  [1,2,3] )
[1, 2, 3]

>>> print( *[1,2,3] )
1 2 3
>>> [ (x, 'added') for x in [(1,2), (3,4), (5,6)]]
[((1, 2), 'added'), ((3, 4), 'added'), ((5, 6), 'added')]

>>> [ (*x, 'added') for x in [(1,2), (3,4), (5,6)]]
[(1, 2, 'added'), (3, 4, 'added'), (5, 6, 'added')]

Unpacking in a for … in loop

Iterable unpacking can also be applied in a for … in loop:
for foo, *bar, baz in [
      ( 'one', 'two', 'three', 'four', 'five' ),
      [    1 ,    2 ,      3 ,             5  ],
    ]:

    print(foo)
    print(bar)
    print(baz)
    print()
Github repository about-Python, path: /iterable/unpacking/for-in.py
This example prints:
one
['two', 'three', 'four']
five

1
[2, 3]
5

Packing

foo, *bar, baz = ( 'one', 'two', 'three', 'four', 'five' )

print(foo) #   one
print(bar) # ['two', 'three', 'four']
print(baz) #   five
Github repository about-Python, path: /iterable/unpacking/assignment.py

Type of an unpacked iterarable

The type of the portion of the iterable that was assigned to the variable with the * is list:
a, *b = (1, 2), 'a', 'b', 'c'

print(type(a))
#
#  <class 'tuple'>

print(type(b))
#
#  <class 'list'>
Github repository about-Python, path: /iterable/unpacking/type.py

See also

A list can be passed to a function as its «individual elements» by prepending the list with a star when the function is called, see unpacking arguments when calling a function.
Sometimes, when unpacking a in iterable into variables, some of these variables are not needed later. This can be indicated by unpacking them into the underscore variable.
Windows/PowerShell: $elem1, $elem2, $rest = $a, $b, $c, $d, $e, $f
Iterable upacking can be seen as a prototype for pattern matching (see PEPs related to Structural Pattern Matching).

Index