What is a good, brief way to extract items from a list and pass them as parameters to a function call, such as in the example below?
Example:
def add(a,b,c,d,e):
print(a,b,c,d,e)
x=(1,2,3,4,5)
add(magic_function(x))
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can unpack a tuple or a list into positional arguments using a star.
def add(a, b, c):
print(a, b, c)
x = (1, 2, 3)
add(*x)
Similarly, you can use double star to unpack a dict into keyword arguments.
x = { 'a': 3, 'b': 1, 'c': 2 }
add(**x)
Method 2
I think you mean the * unpacking operator:
>>> l = [1,2,3,4,5] >>> def add(a,b,c,d,e): ... print(a,b,c,d,e) ... >>> add(*l) 1 2 3 4 5
Method 3
Use the * operator. So add(*x) would do what you want.
See this other SO question for more information.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0