views:

169

answers:

2

Let's say I have a method definition like this:

def myMethod(a, b, c, d, e)

Then, I have a variable and a tuple like this:

myVariable = 1
myTuple = (2, 3, 4, 5)

Is there a way I can pass explode the tuple so that I can pass its members as parameters? Something like this (although I know this won't work as the entire tuple is considered the second parameter):

myMethod(myVariable, myTuple)

I'd like to avoid referencing each tuple member individually if possible...

+14  A: 

You are looking for the argument unpacking operator *:

myMethod(myVariable, *myTuple)
unutbu
Also works for lists (for the benefit of the OP)
Wayne Werner
Also works for iterators.
unutbu
Nice, thanks! (I thought I had read about a method... still pretty new to Python though and wasn't sure how to search for it.)
froadie
@froadie: Right, there used to be -- actually, still is -- a function called `apply` which can serve the same purpose as the star and double-star operators. But `apply` is deprecated in favor of * and **. (See http://docs.python.org/library/functions.html#apply)
unutbu
Also works for iterables, in contradiction to the manual, which says it must be a sequence.
Philipp
+6  A: 

From the Python documentation:

The reverse situation occurs when the arguments are already in a list or tuple but need to be unpacked for a function call requiring separate positional arguments. For instance, the built-in range() function expects separate start and stop arguments. If they are not available separately, write the function call with the *-operator to unpack the arguments out of a list or tuple:

>>> range(3, 6)             # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args)            # call with arguments unpacked from a list
[3, 4, 5]

In the same fashion, dictionaries can deliver keyword arguments with the **-operator:

>>> def parrot(voltage, state='a stiff', action='voom'):
...     print "-- This parrot wouldn't", action,
...     print "if you put", voltage, "volts through it.",
...     print "E's", state, "!"
...
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)
-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
Arrieta