Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python array as list of parameters

Tags:

python

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

like image 890
bdfy Avatar asked Feb 10 '11 17:02

bdfy


People also ask

Can you pass an array as a parameter in Python?

In Python, any type of data can be passed as an argument like string, list, array, dictionary, etc to a function.

Can you convert an array to a list in Python?

We can use NumPy np. array tolist() function to convert an array to a list. If the array is multi-dimensional, a nested list is returned. For a one-dimensional array, a list with the array elements is returned.

How do you pass list elements as parameters in Python?

In Python, you can unpack list , tuple , dict (dictionary) and pass its elements to function as arguments by adding * to list or tuple and ** to dictionary when calling function.

Can I pass list to * args?

yes, using *arg passing args to a function will make python unpack the values in arg and pass it to the function.


2 Answers

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.

like image 101
Reiner Gerecke Avatar answered Oct 06 '22 22:10

Reiner Gerecke


I think what you are looking for is this:

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

arr = [1, 2]
f(*arr)
like image 38
etarion Avatar answered Oct 06 '22 21:10

etarion