199

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() )
Mateusz Piotrowski
  • 8,029
  • 10
  • 53
  • 79
Brian McFarland
  • 9,052
  • 6
  • 38
  • 56
  • Why don't you give a tuple to the function? – lc2817 Oct 12 '11 at 20:16
  • @lc2817 I'm working with a library function that I cannot change and the data passed in as arguments is already in an array. – Brian McFarland Oct 12 '11 at 20:23
  • 8
    I contradict the decision to mark this as a duplicate. Linking to the ``*args`` explanation is correct but claiming this question a duplicate is asking people to play Jeopardy. Only once you know the answer to this question (which is "use *args"), can you know to search for the question claimed to be the duplicate. – Zak May 23 '19 at 12:15

4 Answers4

247

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)
Lee Meador
  • 12,829
  • 2
  • 36
  • 42
Daenyth
  • 35,856
  • 13
  • 85
  • 124
90

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)
varunl
  • 19,499
  • 5
  • 29
  • 47
17

Try the following:

foo(*values)

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

Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
16

That can be done with:

foo(*values)
Ikke
  • 99,403
  • 23
  • 97
  • 120