Ashvin
Ashvin

Reputation: 4020

Is it possible for a python function to return more than 1 value?

I am learning the use of functions in python and want to know if it is possible to return more than 1 value.

Upvotes: 3

Views: 10362

Answers (4)

dheerosaur
dheerosaur

Reputation: 15172

You can return the values you want to return as a tuple.

Example:

>>> def f():
...     return 1, 2, 3
... 
>>> a, b, c = f()
>>> a
1
>>> b
2
>>> c
3
>>>

Upvotes: 7

Lennart Regebro
Lennart Regebro

Reputation: 172249

Python has some parameter unpacking which is cool. So although you can only return one value, if it is a tuple, you can unpack it automatically:

>>> def foo():
...     return 1, 2, 3, 4 # Returns a tuple
>>> foo()
(1, 2, 3, 4)

>>> a, b, c, d = foo()
>>> a
1
>>> b
2
>>> c
3
>>> d
4

In Python 3 you have more advanced features:

>>> a, *b = foo()
>>> a
1
>>> b
[2, 3, 4]
>>> *a, b = foo()
>>> a
[1, 2, 3]
>>> b
4
>>> a, *b, c = foo()
>>> a
1
>>> b
[2, 3]
>>> c
4

But that doesn't work in Python 2.

Upvotes: 7

khachik
khachik

Reputation: 28693

Yes.

def f():
   return 1, 2


x, y = f()
# 1, 2

Upvotes: 1

Marcelo Cantos
Marcelo Cantos

Reputation: 185852

def two_values():
    return (1, 2)

(a, b) = two_values()

Upvotes: 1

Related Questions