Search code examples
pythontuplesparameter-passing

Expanding tuples into arguments


Suppose I have a function like:

def myfun(a, b, c):
    return (a * 2, b + c, c + b)

Given a tuple some_tuple = (1, "foo", "bar"), how would I use some_tuple to call myfun? This should output the result (2, "foobar", "barfoo").

I know could define myfun so that it accepts the tuple directly, but I want to call the existing myfun.


See also: What do ** (double star/asterisk) and * (star/asterisk) mean in a function call? - the corresponding question for people who encounter the syntax and are confused by it.


Solution

  • myfun(*some_tuple) does exactly what you request. The * operator simply unpacks the tuple (or any iterable) and passes them as the positional arguments to the function. Read more about unpacking arguments.