Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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

like image 511
AkiRoss Avatar asked Jan 03 '10 02:01

AkiRoss


People also ask

How do you pass a tuple as an argument?

This method of passing a tuple as an argument to a function involves unpacking method. Unpacking in Python uses *args syntax. As functions can take an arbitrary number of arguments, we use the unpacking operator * to unpack the single argument into multiple arguments.

How do you make a tuple an argument in Python?

The * operator simply unpacks the tuple (or any iterable) and passes them as the positional arguments to the function. Read more about unpacking arguments. The * operator simply unpacks the tuple and passes them as the positional arguments to the function.

Can you extend tuples?

You can't add elements to a tuple because of their immutable property. There's no append() or extend() method for tuples, You can't remove elements from a tuple, also because of their immutability.

How many arguments can a tuple take?

A tuple can be an argument, but only one - it's just a variable of type tuple . In short, functions are built in such a way that they take an arbitrary number of arguments. The * and ** operators are able to unpack tuples/lists/dicts into arguments on one end, and pack them on the other end.


2 Answers

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.

like image 117
Alex Martelli Avatar answered Oct 02 '22 21:10

Alex Martelli


Note that you can also expand part of argument list:

myfun(1, *("foo", "bar")) 
like image 20
Valentas Avatar answered Oct 02 '22 21:10

Valentas