Search code examples
pythonevalargs

passing a tuple in *args


I'd like to pass a tuple (or maybe a list) to a function as a sequence of values (arguments). The tuple should be then unpacked as an argument into *arg.

For example, this is clear:

def func(*args):
    for i in args:
        print "i = ", i

func('a', 'b', 3, 'something')

But what I want to do is this:

tup = ('a1', 'a2', 4, 'something-else')
func(tup)

And this should behave similar to the first case. I think I should use here reprint and eval but not sure how exactly.

I know that I can just pass the tuple in the function and then unpack it within the body, but my question here is how to unpack it in the function call itself.


Solution

  • You can just use func(*tup) to unpack the tuple directly when you invoke the function.

    >>> func(*tup)
    i =  a1
    i =  a2
    i =  4
    i =  something-else
    

    This is kind of equivalent to func(tup[0], tup[1], tup[2], ...). The same also works if the function expects multiple individual parameters:

    >>> def func2(a, b, c, d):
    ...     print(a, b, c, d)
    ...
    >>> func2(*tup)
    ('a1', 'a2', 4, 'something-else')
    

    See e.g. here for more in-depth background on the syntax.