14

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.

Gyan Veda
  • 6,309
  • 11
  • 41
  • 66
  • 6
    `x = function()` also gets both values. If you try that, you'll see that x will be a tuple. – matiasg Apr 24 '15 at 14:48
  • Does this answer your question? [Ignore python multiple return value](https://stackoverflow.com/questions/431866/ignore-python-multiple-return-value) – Josh Correia Feb 03 '21 at 19:43

2 Answers2

28

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

_, y = function()
Mureinik
  • 297,002
  • 52
  • 306
  • 350
10

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.

JuniorCompressor
  • 19,631
  • 4
  • 30
  • 57