How to expand a list to function arguments in Python


Is there syntax that allows you to expand a list into the arguments of a function call?


# 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() )
Asked By: Brian McFarland



Try the following:


This can be found in the Python docs as Unpacking Argument Lists.

Answered By: Andrew Clark

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]

There’s also one for dictionaries to call with named arguments:

d = {'a': 1, 'b': 2}
def foo(a, b):
Answered By: Daenyth

That can be done with:

Answered By: Ikke

You should use the * operator, like foo(*values) Read the Python doc unpackaging argument lists.

Also, do read this:

def foo(x,y,z):
   return "%d, %d, %d" % (x,y,z)

values = [1,2,3]

# the solution.
Answered By: varunl
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.