Return multiple values from a function in python

In python, there is a concept called unpacking values. What it does is, it allows us to assign values to multiple variables together at the same time. I think it is easier to explain this with an example.

unpacking values using python

In this way we can unpack vales using python. But what happens if the variables and the values do not match? Let us find out.

If the variables are less compared to the values to unpack we will get a ValueError like this.

unpack ValueError

The next case is having more variables than the values to unpack. In this case we will get a ValueError like this.

ValueError while unpacking

There is an alternative to this situation. If we are not sure of the number of values to be unpacked but we know the number of variables required, we can declare any of the variables like *variable, which is nothing but a list-like variable. So all the excess values will be stored in this variable as a list.

unpacking values as a list

I hope now you are clear with this concept. We will be using this similar unpacking concept to unpack the many values returned from our function .

Returning multiple values from a function

In python, we can return multiple values from a function separated by a comma. Consider the following program where my function will return four values.

def operation(num1, num2):
    add = num1 + num2
    sub = num1 - num2
    mul = num1 * num2
    div = num1 / num2
    return add, sub, mul, div

The operation() function will take two numbers and perform addition, subtraction, multiplication, and division operations on them. It returns the result of all these four operations separated by a comma.

We can unpack the values in our main program like this.

value1 = 10
value2 = 5
addition, subtraction, multiplication, division = operation(value1, value2)

The addition variable will have the result of the addition operation, subtraction will have the result of the subtraction operation and so on.

The complete code looks like this.

def operation(num1, num2):
    add = num1 + num2
    sub = num1 - num2
    mul = num1 * num2
    div = num1 / num2
    return add, sub, mul, div


value1 = 10
value2 = 5
addition, subtraction, multiplication, division = operation(value1, value2)
print(f"addition result is {addition}")
print(f"subtraction result is {subtraction}")
print(f"multiplication result is {multiplication}")
print(f"division result is {division}")

The output of the above code is,

addition result is 15
subtraction result is 5
multiplication result is 50
division result is 2.0

That is how you will return multiple values from a function and unpack it in your main code.

Conclusion

Hope this article is helpful. If you have any questions leave them in the comments below. I will try to answer them as soon as possible.

Happy coding!