Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing functions which have multiple return values as arguments in Python

So, Python functions can return multiple values. It struck me that it would be convenient (though a bit less readable) if the following were possible.

a = [[1,2],[3,4]]

def cord():
    return 1, 1

def printa(y,x):
    print a[y][x]

printa(cord())

...but it's not. I'm aware that you can do the same thing by dumping both return values into temporary variables, but it doesn't seem as elegant. I could also rewrite the last line as "printa(cord()[0], cord()[1])", but that would execute cord() twice.

Is there an elegant, efficient way to do this? Or should I just see that quote about premature optimization and forget about this?

like image 794
James Avatar asked Mar 27 '09 19:03

James


People also ask

Can a function have multiple return values in Python?

Python functions can return multiple values. These values can be stored in variables directly. A function is not restricted to return a variable, it can return zero, one, two or more values.

Can you pass multiple arguments to a function in Python?

Passing multiple arguments to a function in Python:We can pass multiple arguments to a python function by predetermining the formal parameters in the function definition.

Which allows to return multiple values from a function in Python?

To return multiple values from a function in Python, return a tuple of values. A tuple is a group of comma-separated values. You can create a tuple with or without parenthesis. To access/store the multiple values returned by a function, use tuple destructuring.


2 Answers

printa(*cord())

The * here is an argument expansion operator... well I forget what it's technically called, but in this context it takes a list or tuple and expands it out so the function sees each list/tuple element as a separate argument.

It's basically the reverse of the * you might use to capture all non-keyword arguments in a function definition:

def fn(*args):
    # args is now a tuple of the non-keyworded arguments
    print args

fn(1, 2, 3, 4, 5)

prints (1, 2, 3, 4, 5)

fn(*[1, 2, 3, 4, 5])

does the same.

like image 73
David Z Avatar answered Oct 01 '22 01:10

David Z


Try this:

>>> def cord():
...     return (1, 1)
...
>>> def printa(y, x):
...     print a[y][x]
...
>>> a=[[1,2],[3,4]]
>>> printa(*cord())
4

The star basically says "use the elements of this collection as positional arguments." You can do the same with a dict for keyword arguments using two stars:

>>> a = {'a' : 2, 'b' : 3}
>>> def foo(a, b):
...    print a, b
...
>>> foo(**a)
2 3
like image 44
Jason Baker Avatar answered Oct 01 '22 01:10

Jason Baker