Returning multiple Variables in Python

In the previous article saw how parameters are passed and handled in Python, now we will look at how we can return multiple variables in Python. Here is an example program that returns two values:

def add_multiply(x,y):
    sum=x+y
    mul=x*y
    return sum,mul
s,m=add_multiply(10,20)
print(s)
print(m)
Output:
30
200

When we call the function we receive the two values from add_multiply, later the program prints out the value of both the variables which are initialized with the values from add_multiply. The function stores values in the form of tuple by default.

Working with returning multiple Variables in Python

We can modify the earlier program to accept further values or to perform various different operations. Here is our modified program, it returns three values and perform additional tasks with variables.

def add_multiply_subtract(x,y):
    sum=x+y
    mul=x*y
    sub=x-y
    return sum,mul,sub
s,m,sb=add_multiply_subtract(10,20)
print(s)
print(m)
print(sb)
Output:
30
200
-10

Rather than as a tuple we could also choose to return it as a list or dictionary. In the below code we store elements as in list structure and return list elements with just the simple addition of square brackets.

def add_multiply_subtract(x,y):
    sum=x+y
    mul=x*y
    sub=x-y
    return [sum,mul,sub]
s,m,sb=add_multiply_subtract(10,20)
print(s)
print(m)
print(sb)
Output:
30
200
-10

So there are multiple ways of returning multiple variables in Python but the most straightforward way is to separate them through the use of commas. In the next article we will look at Global Variables in Python.

Leave a Comment