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开发者_如何学C to return more than 1 value.
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.
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
>>>
def two_values():
return (1, 2)
(a, b) = two_values()
Yes.
def f():
return 1, 2
x, y = f()
# 1, 2
精彩评论