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

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

+3
source share
4 answers

Python has a parameter unpacking package, which is cool. Therefore, 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 this does not work in Python 2.

+7
source

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
>>>
+7
source
def two_values():
    return (1, 2)

(a, b) = two_values()
+1

.

def f():
   return 1, 2


x, y = f()
# 1, 2
+1

Source: https://habr.com/ru/post/1781970/


All Articles