Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore an output of a multi-output function in Python? [duplicate]

Suppose I have a function:

def f():
  ...
  ...
  ...
  return a,b,c

and I want to get only b in output of the function. Which assignment I have to use?

Thanks.

like image 576
Cupitor Avatar asked Mar 24 '13 19:03

Cupitor


People also ask

How do you return multiple things from a function in Python?

In Python, you can return multiple values by simply return them separated by commas. In Python, comma-separated values are considered tuples without parentheses, except where required by syntax. For this reason, the function in the above example returns a tuple with each value as an element.

How do you return a single value from a function in Python?

You can use x = func()[0] to return the first value, x = func()[1] to return the second, and so on. If you want to get multiple values at a time, use something like x, y = func()[2:4] . This should be the accepted answer.


2 Answers

You can unpack the returned tuple into some dummy variables:

_, keep_this, _ = f()

It doesn't have to be _, just something obviously unused.

(Don't use _ as a dummy name in the interactive interpreter, there it is used for holding the last result.)

 

Alternatively, index the returned tuple:

keep_this = f()[1]
like image 189
Pavel Anossov Avatar answered Oct 07 '22 04:10

Pavel Anossov


def f():
    return 1,2,3

here, f() returns a tuple (1,2,3) so you can do something like this:

a = f()[0]
print a
1

a = f()[1]
print a
2

a = f()[2]
print a
3
like image 27
zenpoy Avatar answered Oct 07 '22 02:10

zenpoy