Python 3: starred expression to unpack a list

My example is:

>>> 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

To understand it thoroughly I would like to consult the documentation about that '*'.

Could you suggest me where to look?


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.

链接地址: http://www.djcxy.com/p/53554.html

上一篇: 有没有办法在不使用Python中的方括号的情况下初始化列表?

下一篇: Python 3:用星号表达来解压缩列表