10

I have a function that most of the time should return a single value, but sometimes I need a second value returned from the function. Here I found how to return multiple values, but as most of the time I need only one of them I would like to write something like this:

def test_fun():
    return 1,2

def test_call():
    x = test_fun()
    print x

but calling this results in

>>> test_call()
(1,2)

and when trying to return more than two, as in

def test_fun2():
    return 1,2,3

def test_call2():
    x,y = test_fun2()
    print x,y

I get an error

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "my_module.py", line 47, in test_call2
    x,y = test_fun2()
ValueError: too many values to unpack

I am thinking about something like in matlab, where x = test_fun() would result in x == 1 (while [x y] = test_fun() would also work as expected). Is something like that possible in python?

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185

2 Answers2

18

You can use star unpacking to gather all additional return values into a list:

x, *y = fun()

x will contain the first return value. y will be a list of the remaining values. y will be empty if there is only one return value. This particular example will only work if the function returns a tuple, even if there is only one value.

When fun always returns 1 or 2 values, you can just do

if y:
    print(y[0])
else:
    print('only one value')

If, on the other hand, you want to completely ignore the number of return values, do

*x = fun()

Now all the arguments will be gathered into the list. You can then print it with either

print(x)

or

print(*x)

The latter will pass each element as a separate argument, exactly as if you did

x, y, z = fun()
print(x, y, z)

The reason to use *x = fun() instead of just x = fun() is to get an error immediately when a function returns something that isn't a tuple. Think of it as an assertion to remind you to write fun properly.

Since this form of star unpacking only works in Python 3, your only option in Python 2 is to do

x = fun()

and to inspect the result manually.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
1

There are several ways to get multiple return values.

Example 1:

def test_fun():
    return 1,2

def test_call():
    x, y = test_fun()
    print x
    print y

you will get correct output:

1
2

When you would like to ignore several return values, you can use * before a variable in python3.

Example 2:

def test_fun2():
    return 1,2,3

def test_call2():
    x, *y = test_fun2()
    print x
    print y

you will get the result:

1
(2, 3)
blanksky
  • 13
  • 4