Python 3: starred expression to unpack a list

Kifsif picture Kifsif · Sep 23, 2012 · Viewed 43.6k times · Source

Example use:

def f(a, b, c, d): 
    print(a, b, c, d, sep = '&')

f(1,2,3,4)
>>> 1&2&3&4

f(*[1, 2, 3, 4])
>>> 1&2&3&4

Where in the python documentation is * explained?

Answer

Martijn Pieters picture Martijn Pieters · Sep 26, 2012

The *args calling convention is documented in the Expressions reference:

If the syntax *expression appears in the function call, expression must evaluate to an iterable. Elements from this iterable are treated as if they were additional positional arguments; if there are positional arguments x1, ..., xN, and expression evaluates to a sequence y1, ..., yM, this is equivalent to a call with M+N positional arguments x1, ..., xN, y1, ..., yM.

So, since you used [1, 2, 3, 4] as the expression, which is an iterable, and there were no other positional arguments, it is treated as a call with M=0 and N=4, for a total of 4 positional arguments.

You can thus also call your function as f(1, 2, *[3, 4]) or any other combination of iterable and positional arguments, provided the iterable comes after the positionals.