Flatten a list/tuple and Call a function with tuples

Stargaming stargaming at gmail.com
Wed Jul 25 18:23:04 CEST 2007


On Wed, 25 Jul 2007 15:46:58 +0000, beginner wrote:

> On Jul 25, 10:19 am, Stargaming <stargam... at gmail.com> wrote:
>> On Wed, 25 Jul 2007 14:50:18 +0000, beginner wrote:
[snip]
>>
>> > Another question is how do I pass a tuple or list of all the
>> > aurgements of a function to the function. For example, I have all the
>> > arguments of a function in a tuple a=(1,2,3). Then I want to pass
>> > each item in the tuple to a function f so that I make a function call
>> > f(1,2,3). In perl it is a given, but in python, I haven't figured out
>> > a way to do it. (Maybe apply? but it is deprecated?)
>> >>> def foo(a, b, c): print a, b, c
>> ...
>> >>> t = (1, 2, 3)
>> >>> foo(*t)
>>
>> 1 2 3
>>
>> Have a look at the official tutorial, 4.7.4http://www.python.org/doc/
>> current/tut/node6.html#SECTION006740000000000000000
>>
>> > Thanks,
>> > cg
>>
>> HTH,
>> Stargaming
> 
> Hi Stargaming,
> 
> I know the * operator. However, a 'partial unpack' does not seem to
> work.
> 
> def g():
>   return (1,2)
> 
> def f(a,b,c):
>   return a+b+c
> 
> f(*g(),10) will return an error.

http://docs.python.org/ref/calls.html

> Do you know how to get that to work?

Well, there are several ways to solve this. You could either invoke f(*g
() + (10,)). Might be a bit nasty and unreadable, though. Or you could 
just change your function f to accept them in reversed order (f(10, *g) 
should work) or convert g() to return a dictionary like {'b': 1, 'c': 2} 
and use f(10, **g). But if your function f's hugest use case is being 
called with g(), changing f to accept something and g's result (tuple) -- 
unpacking it inside f -- might be better.



More information about the Python-list mailing list