Python 3: Expand Arguments from a Tuple

Given the Python tuple, is t = v1, v2, v3there a utility for unpacking them so that this one:

def foo(v1,v2,v3): pass

Instead of this:

foo(t[0],t[1],t[2])

You can do it:

foo(unpack(t))

I would like to know about any such utility available for tuples and / or lists.

Sincere thanks.

+5
source share
3 answers

Yeah. You can use the unpack operator ( '*')

foo(*t)

Note that this works if t is list, tupleor even a generator


There is a similar way to pass arguments to keyword functions using an operator **to match objects (usually dictionaries):

def foo(key=None,foo=None):
    pass #...

foo(**{key:1,foo:2})
+14
source

Unpack argument list:

foo(*(v1, v2, v3))
+2
source

Use argument *args:

foo(*t)

Demo:

>>> def foo(v1, v2, v3):
...     print(v1, v2, v3)
...
>>> t = 1, 2, 3
>>> foo(*t)
1 2 3 
+1
source

All Articles