Returning Multiple Values in Python using function

Functions are use to some repetitive activity to avoid adding same code multiple times. Functions sometime return a value  but sometimes may not even return anything, however, you might run into situations where you may want to return multiple values by using function. When you use return statement, it will return the  only one variable. But if you need multiple values, what can be done ?

This can be achieved by using multiple ways, your creativity is the limit, thats the beauty of any programming language.

Two most easiest ways are as below

  1. Return dictionary, tuple or list
  2. Return multiple variables at the same time

Returning dictionary, tuple or list

Here, you simply create a variable of datatype that can store multiple values such as dictionary, tuple or list.  This will add few lines of coding and code might not look as structured and beautiful as you wish but this works

Return multiple variables at the same time

This is nothing but above mentioned method, except, you delegate variable creation to python. Python will create a return a tuple having required values. You still need to take care while receiving the values.

Here is the sample code

def get_add_and_multi(num1,num2):
add = num1+num2
mult = num1*num2
return add,mult

result = get_add_and_multi(2,3)

add, mult = get_add_and_multi(2,3)

print("result :", result, "Datatype is :", type(result))
print("add :", add , "Datatype is :", type(add))
print("mult :", mult,"Datatype is :", type(mult))

As you can see, there are two ways of receiving data.

Output of this code is as below. Please note the data types

$ python3.6 
result : (5, 6) Datatype is : <class 'tuple'>
add : 5 Datatype is : <class 'int'>
mult : 6 Datatype is : <class 'int'>

Leave a Reply

Your email address will not be published. Required fields are marked *