The following works beautifully in Python:
def f(x,y,z): return [x,y,z]
a=[1,2]
f(3,*a)
The elements of a get unpacked as if you had called it like f(3,1,2) and it returns [3,1,2]. Wonderful!
But I can’t unpack the elements of a into the first two arguments:
f(*a,3)
Instead of calling that like f(1,2,3), I get “SyntaxError: only named arguments may follow *expression”.
I’m just wondering why it has to be that way and if there’s any clever trick I might not be aware of for unpacking arrays into arbitrary parts of argument lists without resorting to temporary variables.
As Raymond Hettinger’s answer points out, this
may changehas 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:
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: