ppizarror
ppizarror

Reputation: 31

Passing several arguments from an array to a function in a easy way

Well I really don't know how to describe this in words but I've an easy example:

def foo(x,y,z):
     r=x+....

a = [1,2,3]
foo(a[0], a[1], a[2])

Can I do the same without calling a[n] several times? but keeping "x,y,z" definition?

Upvotes: 1

Views: 83

Answers (3)

Bhargav Rao
Bhargav Rao

Reputation: 52071

Use the unpacking operator!

>>> def foo(x,y,z):
...     return x+y+z
... 
>>> a = [1,2,3]
>>> foo(*a)
6

From the documentation

If they are not available separately, write the function call with the *-operator to unpack the arguments out of a list or tuple:

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

Upvotes: 4

farhawa
farhawa

Reputation: 10398

Try this

def foo(x,y,z):
     r=x+....

a = [1,2,3]
foo(*a)

Upvotes: 1

Kasravnd
Kasravnd

Reputation: 107287

Yeah use unpacking operator to pass any arbitrary arguments to your function :

def foo(*args):
     for i in args : # you can iterate over args or get its elements by indexing
         #do stuff

a = [1,2,3]
foo(*a)

And if you just pass 3 argument you can use unpacking in call time.

def foo(x,y,z):
     r=x+....

a = [1,2,3]
foo(*a)

Upvotes: 1

Related Questions