23

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

SilentGhost
  • 287,765
  • 61
  • 300
  • 288
froadie
  • 75,789
  • 72
  • 163
  • 232
  • Possible duplicate of [Expanding tuples into arguments](https://stackoverflow.com/questions/1993727/expanding-tuples-into-arguments) – Ken Syme Jul 21 '17 at 10:43

2 Answers2

44

You are looking for the argument unpacking operator *:

myMethod(myVariable, *myTuple)
unutbu
  • 777,569
  • 165
  • 1,697
  • 1,613
  • 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 Jul 07 '10 at 19:47
  • @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 Jul 07 '10 at 22:57
  • 1
    Also works for iterables, in contradiction to the manual, which says it must be a sequence. – Philipp Jul 08 '10 at 14:14
7

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 !
Escualo
  • 38,824
  • 20
  • 81
  • 128