Return Multiple Values From a Function in Python

In [1]:
!python --version
Python 3.6.10 :: Anaconda, Inc.

Let us define a function which returns single value.

In [2]:
def demoReturnOne(m):
    return(m)
In [3]:
result = demoReturnOne(7)
In [4]:
print(result)
7
In [5]:
print(type(result))
<class 'int'>

Notice above the type of object returned, it is int.

Return multiple values from Python function using tuple

In [6]:
def demoReturnTwo(m,n):
    return(m,n)
In [7]:
result = demoReturnTwo(1,2)
In [8]:
result
Out[8]:
(1, 2)
In [9]:
print(type(result))
<class 'tuple'>

Note the type 'tuple'.

we can also collect the result in two variables since function is returning a tuple of two elements.

In [10]:
r1, r2 = demoReturnTwo(1,2)
In [11]:
r1
Out[11]:
1
In [12]:
r2
Out[12]:
2

Return multiple values from Python function using List

Let us define a function which returns list.

In [13]:
def listF(m,n):
    return([m,n])
In [14]:
result = listF(1,2)
In [15]:
result
Out[15]:
[1, 2]
In [16]:
print(type(result))
<class 'list'>

We can also assign data to two variables since list contains two elements.

In [17]:
a,b = listF(1,2)
In [18]:
a
Out[18]:
1
In [19]:
b
Out[19]:
2

Similarly we can extend the above concept to function with more than two variables.

In [20]:
def listF(m,n,k):
    return([m,n,k])
In [21]:
result = listF(4,5,6)
In [22]:
result
Out[22]:
[4, 5, 6]
In [23]:
a,b,c = listF(4,5,6)
In [24]:
a
Out[24]:
4
In [25]:
b
Out[25]:
5
In [26]:
c
Out[26]:
6