Unpacking arguments: only named arguments may follow *expression

Solution 1:

As Raymond Hettinger's answer points out, this may change has changed in Python 3 and here is a related proposal, which has been accepted. Especially related to the current question, here's one of the possible changes to that proposal that was discussed:

Only allow a starred expression as the last item in the exprlist. This would simplify the unpacking code a bit and allow for the starred expression to be assigned an iterator. This behavior was rejected because it would be too surprising.

So there are implementation reasons for the restriction with unpacking function arguments but it is indeed a little surprising!

In the meantime, here's the workaround I was looking for, kind of obvious in retrospect:

f(*(a+[3]))

Solution 2:

It doesn't have to be that way. It was just rule that Guido found to be sensible.

In Python 3, the rules for unpacking have been liberalized somewhat:

>>> a, *b, c = range(10)
>>> a
0
>>> b
[1, 2, 3, 4, 5, 6, 7, 8]
>>> c
9

Depending on whether Guido feels it would improve the language, that liberalization could also be extended to function arguments.

See the discussion on extended iterable unpacking for some thoughts on why Python 3 changed the rules.

Solution 3:

Thanks to the PEP 448 - Additional Unpacking Generalizations,

f(*a, 3)

is now accepted syntax starting from Python 3.5. Likewise you can use the double-star ** for keyword argument unpacking anywhere and either one can be used multiple times.