Rats! vararg assignments don't work
Gary Herron
gherron at islandtraining.com
Wed May 30 02:38:38 EDT 2007
samwyse wrote:
> I'm a relative newbie to Python, so please bear with me. After seeing
> how varargs work in parameter lists, like this:
> def func(x, *arglist):
> and this:
> x = func(1, *moreargs)
> I thought that I'd try this:
> first, *rest = arglist
> Needless to say, it didn't work. That leaves me with two questions.
>
> First, is there a good way to do this? For now, I'm using this:
> first, rest = arglist[0], arglist[1:]
> but it leaves a bad taste in my mouth.
>
Well, your moreargs parameter is a tuple, and there are innumerable ways
to process a tuple. (And even more if you convert it to a list.)
If you are just interested in extracting only the first arg, then your
code is quite Pythonic. However, if you are going to do that in a loop
to successively process each arg, the you have several better options:
For instance:
for arg in moreargs: # Loop through each arg
<do something with arg>
or
for i in range(len(moreargs)):
<do something with morergs[i]> # Extract ith arg
or
argslist = list(moreargs)
while argslist:
firstarg = argslist.pop(0) # Extract first arg
<do something with firstarg>
Gary Herron
> Second, is there any good reason why it shouldn't work? It seems like
> such an obvious idiom that I can't believe that I'm the first to come up
> with the idea. I don't really have the time right now to go source
> diving, so I can't tell if it would be wildly inefficient to implement.
>
> Thanks!
>
More information about the Python-list
mailing list