Using an interable in place of *args?

Bengt Richter bokr at oz.net
Fri Nov 21 11:57:11 EST 2003


On 21 Nov 2003 11:49:45 -0500, Nick Vargish <nav+posts at bandersnatch.org.invalid> wrote:

>Greetings,
>
>
>Is there a general method for calling a function that expects *args
>with an iterable instead (tuple or, even better, a list)? I can see
>how I could do something funky with exec, but I'd like to avoid that
>if possible.

 >>> def foo(*args): print args
 ...
 >>> foo(*[x for x in 'You mean like this ?'.split()])
 ('You', 'mean', 'like', 'this', '?')

(just prefix '*' to unpack a sequence into the arg list)

You can even unpack a generator-supplied sequence:

 >>> def g():
 ...    for x in 'You mean like this ?'.split(): yield x
 ...
 >>> foo(*g())
 ('You', 'mean', 'like', 'this', '?')

It's not limited to passing args to *args on the receiving end either, though
the count has to match if it's fixed:

 >>> def bar(x,y,z): print x,y,z
 ...
 >>> bar(*'this works too'.split())
 this works too

 >>> bar(*'but this does not, since the count is wrong.'.split())
 Traceback (most recent call last):
   File "<stdin>", line 1, in ?
 TypeError: bar() takes exactly 3 arguments (9 given)

Regards,
Bengt Richter




More information about the Python-list mailing list