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.
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.
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.
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(_).
No, you can not have two returns in a function, the first return will exit the function you will need to create an object.
The pythonic idiom is just to ignore the first return value by assigning it to _
:
_, y = function()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With