46

Given the definitions:

def egg2(arg1, arg2):
    print arg1
    print arg2

argList = ["egg1", "egg2"]

How can I simply call egg2 using the list? I want the same effect as egg2(argList[0], argList[1]), but without having to index each element explicitly.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Rohita Khatiwada
  • 2,835
  • 9
  • 40
  • 52
  • 5
    possible duplicate of [Pass each element of a list to a function that takes multiple arguments in Python?](http://stackoverflow.com/questions/3558593/pass-each-element-of-a-list-to-a-function-that-takes-multiple-arguments-in-python) – Felix Kling Aug 02 '11 at 13:54
  • Does this answer your question? [Pass each element of a list to a function that takes multiple arguments in Python?](https://stackoverflow.com/questions/3558593/pass-each-element-of-a-list-to-a-function-that-takes-multiple-arguments-in-pytho) – xskxzr Aug 09 '21 at 08:21
  • This version of the question looks better overall than the other one, but there might yet be something better. I don't want to route this to the canonical explaining `*args` in function calls, because this question is the other way around: how to do it, rather than what the syntax means. – Karl Knechtel Jan 24 '23 at 15:32

4 Answers4

94
>>> argList = ["egg1", "egg2"]
>>> egg2(*argList)
egg1
egg2

You can use *args (arguments) and **kwargs (for keyword arguments) when calling a function. Have a look at this blog on how to use it properly.

Jacob
  • 41,721
  • 6
  • 79
  • 81
15

There is a special syntax for argument unpacking:

egg2(*argList)
Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
1

There are maybe better ways, but you can do:

argList = ["egg1", "egg2"]
(a, b) = tuple(argList)
egg2(a, b)
MByD
  • 135,866
  • 28
  • 264
  • 277
0

arg.split() does not split the list the way you want because the default separator does not match yours:

In [3]: arg
Out[3]: 'egg1, egg2'

In [4]: arg.split()
Out[4]: ['egg1,', 'egg2']

In [5]: arg.split(', ')
Out[5]: ['egg1', 'egg2']

From the docs (emphasis added):

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

matt b
  • 138,234
  • 66
  • 282
  • 345
  • 2
    It's not immediately clear to me that this addresses the fundamental problem, which is that `eggs2` requires two arguments, but any variation on `['egg1', 'egg2'] is a single argument unless preceded by the `*` operator. – senderle Aug 02 '11 at 14:18