To return multiple values from a function in Python, you can use the return keyword and separate the values by commas. To access the returned values, use tuple unpacking.

def function_return_multiple():
    return 0, 1, 2, 3

a, b, c, d = function_return_multiple()

print(a)
print(b)
print(c)
print(d)

#Output:
0
1
2
3

You can also return multiple values as a list and then access the values just like you would access an item in a list.

def function_return_multiple():
    return 0, 1, 2, 3

a = function_return_multiple()

print(a)

#Output:
[0, 1, 2, 3]

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 multiple 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 multiple values from a function in Python, you can use the return keyword and separate the values by commas. To access the returned values, use tuple unpacking.

Below shows you a simple example of how you can use tuple unpacking to return multiple values from a function in Python.

def function_return_multiple():
    return 0, 1, 2, 3

a, b, c, d = function_return_multiple()

print(a)
print(b)
print(c)
print(d)

#Output:
0
1
2
3

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 multiple values from a function in Python.

def function_return_multiple():
    return 0, 1, 2, 3

a, *b = function_return_multiple()

print(a)
print(b)

#Output:
0
[1, 2, 3]

Return Multiple Values from Function as List in Python

Another way you can return multiple 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 multiple values as a list in Python.

def function_return_multiple():
    return 0, 1, 3,4 

a = function_return_multiple()

print(a)

#Output:
[0, 1, 2, 3]

Hopefully this article has been useful for you to understand how to return multiplevalues from a function in Python.

Categorized in:

Python,

Last Update: March 11, 2024