Expanding tuples into arguments

AkiRoss picture AkiRoss · Jan 3, 2010 · Viewed 243.1k times · Source

Is there a way to expand a Python tuple into a function - as actual parameters?

For example, here expand() does the magic:

some_tuple = (1, "foo", "bar")

def myfun(number, str1, str2):
    return (number * 2, str1 + str2, str2 + str1)

myfun(expand(some_tuple)) # (2, "foobar", "barfoo")

I know one could define myfun as myfun((a, b, c)), but of course there may be legacy code. Thanks

Answer

Alex Martelli picture Alex Martelli · Jan 3, 2010

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.