bdfy
bdfy

Reputation: 191

python array as list of parameters

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])?

Upvotes: 16

Views: 31576

Answers (3)

Reiner Gerecke
Reiner Gerecke

Reputation: 12214

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.

Upvotes: 40

Kevin Dolan
Kevin Dolan

Reputation: 5097

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.

Upvotes: 2

etarion
etarion

Reputation: 17131

I think what you are looking for is this:

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

arr = [1, 2]
f(*arr)

Upvotes: 17

Related Questions