16

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

2
  • 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) Commented Feb 10, 2011 at 17:48
  • 2
    possible duplicate of How can I explode a tuple so that it can be passed as a parameter list? Commented Feb 10, 2011 at 18:04

3 Answers 3

40

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.

Sign up to request clarification or add additional context in comments.

Comments

17

I think what you are looking for is this:

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

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

3 Comments

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...
Hard to find when you do know the name! Thanks for giving it out ;)
@Atais, Don't worry: guys like delnan assume that because they know how to find something, everyone else does too.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.