55

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?

iacob
  • 20,084
  • 6
  • 92
  • 119
Kifsif
  • 3,477
  • 10
  • 36
  • 45
  • 2
    Related question: http://stackoverflow.com/questions/6967632/getting-python-sequence-assignments-unpacking-right – Lev Levitsky Sep 23 '12 at 19:41
  • 2
    The relevant portion of the language reference is here: http://docs.python.org/dev/reference/expressions.html#calls . Look for the sentence starting "If the syntax *expression appears in the function call" – Mark Dickinson Sep 23 '12 at 20:09
  • 2
    Good explanation here: http://stackoverflow.com/questions/5239856/foggy-on-asterisk-in-python – Alex W Sep 26 '12 at 02:45

2 Answers2

62

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
7

Just an addition to very simply expand on the combination of unnamed and named arguments.

This is the general order you want to keep in mind:

def func(arg_1, ..., arg_N, *args, kwarg_1, ..., kwarg_M, **kwargs):
    # do stuff
    return True

Where, in most typical cases;

  • each single arg_i is an unnamed argument,
  • args is a list, hence a set of unnamed arguments,
  • each single kwarg_j is a named argument,
  • kwargs is a dictionary, hence a set of named arguments.
swiss_knight
  • 5,787
  • 8
  • 50
  • 92