Expanding tuples into arguments


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

For example, here expand() does the magic:

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

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

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

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

9/29/2013 4:01:32 PM

Accepted Answer

myfun(*tuple) does exactly what you request.

Side issue: don't use as your identifiers builtin type names such as tuple, list, file, set, and so forth -- it's horrible practice and it will come back and bite you when you least expect it, so just get into the habit of actively avoiding hiding builtin names with your own identifiers.

1/10/2018 2:45:26 PM

Note that you can also expand part of argument list:

myfun(1, *("foo", "bar"))

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow