15

I have an array that matches the parameters of a function:

        TmpfieldNames = []
        TmpfieldNames.append(Trademark.name)
        TmpfieldNames.append(Trademark.id)
        return func(Trademark.name, Trademark.id)

func(Trademark.name.Trademark.id) works, but func(TmpfieldNames) doesn't. How can I call the function without explicitly indexing into the array like func(TmpfieldNames[0], TmpfieldNames[1])?

Stan Kurdziel
  • 5,476
  • 1
  • 43
  • 42
bdfy
  • 181
  • 1
  • 1
  • 3
  • That code doesn't make sense. You're just filling a list with `len(fieldNames)` copies of (references to) `Tademark.id`, then return the result of some function called with a single `Trademark.name` and `Trademark.id`. (Edit: Okay, that makes more sense) –  Feb 10 '11 at 17:48
  • 2
    possible duplicate of [How can I explode a tuple so that it can be passed as a parameter list?](http://stackoverflow.com/questions/3198218/how-can-i-explode-a-tuple-so-that-it-can-be-passed-as-a-parameter-list) – etarion Feb 10 '11 at 18:04

3 Answers3

39

With * you can unpack arguments from a list or tuple and ** unpacks arguments from a dict.

>>> range(3, 6)             # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args)            # call with arguments unpacked from a list
[3, 4, 5]

Example from the documentation.

Stan Kurdziel
  • 5,476
  • 1
  • 43
  • 42
Reiner Gerecke
  • 11,936
  • 1
  • 49
  • 41
17

I think what you are looking for is this:

def f(a, b):
    print a, b

arr = [1, 2]
f(*arr)
etarion
  • 16,935
  • 4
  • 43
  • 66
  • 2
    For the record, it's called argument unpacking and we already had it a dozen times on SO alone, not to mention all the Python tutorials... –  Feb 10 '11 at 17:50
  • 2
    Hard to find when you do know the name! Thanks for giving it out ;) – Atais Jan 18 '15 at 19:27
  • @Atais, Don't worry: guys like delnan assume that because they know how to find something, everyone else does too. – user1717828 Jan 22 '16 at 23:06
2

What you are looking for is:

func(*TmpfieldNames)

But this isn't the typical use case for such a feature; I'm assuming you've created it for demonstration.

Kevin Dolan
  • 4,952
  • 3
  • 35
  • 47