2

Is it possible to use a single data structure to pass into a function with multiple arguments? I'd like to do something like the following but it doesn't appear to work.

foo_bar = (123, 546)

def a(foo, bar):
    print(foo)
    print(bar)

Is it possible to do something like the following:

a(foo_bar)

instead of:

a(foo_bar[0], foo_bar[1])

What is the pythonic way of doing this?

mandroid
  • 2,308
  • 5
  • 24
  • 37

1 Answers1

16

What you want is:

a(*foo_bar)

See Unpacking Argument Lists in the tutorial for details… but there really isn't much more to it than this.

For completeness, the reference documentation is in Calls:

If the syntax *expression appears in the function call, expression must evaluate to an iterable. Elements from this iterable are treated as if they were additional positional arguments; if there are positional arguments x1, ..., xN, and expression evaluates to a sequence y1, ..., yM, this is equivalent to a call with M+N positional arguments x1, ..., xN, y1, ..., yM.

abarnert
  • 354,177
  • 51
  • 601
  • 671
  • 1
    see http://stackoverflow.com/questions/817087/call-a-function-with-argument-list-in-python – Joe F Apr 19 '13 at 00:10