Is there syntax that allows you to expand a list into the arguments of a function call?
Example:
# Trivial example function, not meant to do anything useful. def foo(x,y,z): return "%d, %d, %d" %(x,y,z) # List of values that I want to pass into foo. values = [1,2,3] # I want to do something like this, and get the result "1, 2, 3": foo( values.howDoYouExpandMe() )
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
It exists, but it’s hard to search for. I think most people call it the “splat” operator.
It’s in the documentation as “Unpacking argument lists“.
You’d use it like this for positional arguments:
values = [1, 2] foo(*values)
There’s also one for dictionaries to call with named arguments:
d = {'a': 1, 'b': 2}
def foo(a, b):
pass
foo(**d)
Method 2
You should use the * operator, like foo(*values) Read the Python doc unpackaging argument lists.
Also, do read this: http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/
def foo(x,y,z): return "%d, %d, %d" % (x,y,z) values = [1,2,3] # the solution. foo(*values)
Method 3
Try the following:
foo(*values)
This can be found in the Python docs as Unpacking Argument Lists.
Method 4
That can be done with:
foo(*values)
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