Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass tuples elements to a function as arguments?

I have a list consisting of tuples, I want to pass each tuple's elements to a function as arguments:

mylist = [(a, b), (c, d), (e, f)]

myfunc(a, b)
myfunc(c, d)
myfunc(e, f)

How do I do it?

like image 898
alwbtc Avatar asked May 16 '12 19:05

alwbtc


People also ask

Can I pass a tuple as argument in Python?

A tuple can also be passed as a single argument to the function. Individual tuples as arguments are just individual variables. A function call is not an assignment statement; it's a reference mapping.

Can a function take a tuple as an argument?

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.

How do you pass multiple tuples as parameters in Python?

To expand tuples into arguments with Python, we can use the * operator. to unpack the tuple (1, 2, 3) with * as the arguments of add . Therefore, a is 1, b is 2, and c is 3. And res is 6.


1 Answers

This is actually very simple to do in Python, simply loop over the list and use the splat operator (*) to unpack the tuple as arguments for the function:

mylist = [(a, b), (c, d), (e, f)]
for args in mylist:
    myfunc(*args)

E.g:

>>> numbers = [(1, 2), (3, 4), (5, 6)]
>>> for args in numbers:
...     print(*args)
... 
1 2
3 4
5 6
like image 153
Gareth Latty Avatar answered Sep 20 '22 21:09

Gareth Latty