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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With