Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a Python function return only the second of two values?

I have a Python function that returns multiple values. As an example for this question, consider the function below, which returns two values.

def function():
    ...
    return x, y

I know this function can return both values x, y = function(). But is it possible for this function to only return the second value?

In MATLAB, for example, it would be possible to do something like this: ~, y = function(). I have not found an equivalent approach in Python.

like image 548
Gyan Veda Avatar asked Apr 24 '15 14:04

Gyan Veda


People also ask

Can a Python function only return one value?

Unlike other programming languages, python functions are not restricted to return a single type of value. If you look at the function definition, it doesn't have any information about what it can return.

How do I return more than 2 values 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.

How do you ignore a value in Python?

Underscore(_) is also used to ignore the values. If you don't want to use specific values while unpacking, just assign that value to underscore(_).

Can one function return two values?

No, you can not have two returns in a function, the first return will exit the function you will need to create an object.


2 Answers

The pythonic idiom is just to ignore the first return value by assigning it to _:

_, y = function()
like image 71
Mureinik Avatar answered Oct 21 '22 16:10

Mureinik


The closest syntax you are looking is:

function()[1]

which will return the second element, since function's result can be considered a tuple of size 2.

like image 42
JuniorCompressor Avatar answered Oct 21 '22 16:10

JuniorCompressor