To return two values from a function in Python, you can use the return keyword and separate the values by commas. To access the two returned values, use tuple unpacking.
def function_return_two():
return 0, 1
a, b = function_return_two()
print(a)
print(b)
#Output:
0
1
You can also return two values as a list and then access the values just like you would access an item in a list.
def function_return_two():
return 0, 1
a = function_return_two()
print(a)
#Output:
[0, 1]
When working with functions in Python, sometimes it can make sense where you want to return more than one value from a function.
To return two or more values from a function, you can use the concept of tuple unpacking.
Tuple unpacking allows you create a tuple and then create variables from the elements of the created tuple.
So, to return two values from a function in Python, you can use the return keyword and separate the values by commas. To access the two returned values, use tuple unpacking.
Below shows you a simple example of how you can use tuple unpacking to return two values from a function in Python.
def function_return_two():
return 0, 1
a, b = function_return_two()
print(a)
print(b)
#Output:
0
1
Return Two Values from Function as List in Python
Another way you can return two values from a function is by doing the same as above but instead of creating multiple variables, just create 1 variable.
Then to access the values, you can access them just like you would access an item in a list.
Below shows a simple example of how you can return two values as a list in Python.
def function_return_two():
return 0, 1
a = function_return_two()
print(a)
#Output:
[0, 1]
Return Multiple Values from Function in Python
If you want to return multiple values from a function in Python, then you can use the method shown above and separate additional variables by commas.
Below shows an example of how you can return three values from a function in Python.
def function_return_three():
return 0, 1, 2
a, b, c = function_return_three()
print(a)
print(b)
print(c)
#Output:
0
1
2
One thing to note here is that if you only care about the first few values, then if you don’t unpack all of the values, you will get a ValueError.
The ValueError occurs because you need to unpack all of the values returned.
If you don’t want to unpack all of the values, then you can use the unpacking operator *. This will return the remaining as a list.
Below shows you how to use the unpacking operator when returning more than two values from a function in Python.
def function_return_three():
return 0, 1, 2
a, *b = function_return_three()
print(a)
print(b)
#Output:
0
[1, 2]
Hopefully this article has been useful for you to understand how to return two values from a function in Python.