Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore python multiple return value

Say I have a Python function that returns multiple values in a tuple:

def func():     return 1, 2 

Is there a nice way to ignore one of the results rather than just assigning to a temporary variable? Say if I was only interested in the first value, is there a better way than this:

x, temp = func() 
like image 230
Mat Avatar asked Jan 10 '09 22:01

Mat


People also ask

How Python can handle multiple return values?

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.

What happens if you don't return a value in Python?

So, if you don't explicitly use a return value in a return statement, or if you totally omit the return statement, then Python will implicitly return a default value for you. That default return value will always be None .

Is return None Pythonic?

Python returns null function | Example code Example Python return null (None). To literally return 'nothing' use pass , which basically returns the value None if put in a function(Functions must return a value, so why not 'nothing'). You can do this explicitly and return None yourself though.


1 Answers

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].

like image 171
Luke Woodward Avatar answered Sep 27 '22 21:09

Luke Woodward