Using an interable in place of *args?

Bengt Richter bokr at
Fri Nov 21 17:57:11 CET 2003

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

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

Bengt Richter

More information about the Python-list mailing list