How to ignore output of multi-output function in Python?

Suppose I have a function:

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

and I want to get only b in the output of the function. What purpose should I use?

Thanks.

+8
function python output
source share
3 answers

You can unpack the returned tuple into some dummy variables:

 _, keep_this, _ = f() 

It should not be _ , just something is not explicitly used.

(Do not use _ as a dummy name in the interactive interpreter, there it is used to store the last result.)

Also, index the returned tuple:

 keep_this = f()[1] 
+21
source share
 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 
+3
source share

What you do with the return a,b,c creates a tuple and then returns it from the function. That way you can use tuple decomposition to get only the values ​​you want to get. Example:

 def f(x): return x, x + 1, x + 2 _, b, _ = f(0) print(b) # prints "1" 
+1
source share

All Articles