Returning multiple values in Python

Hello Pythoneers,
In this tutorial, we will learn how to return multiple values in Python. Returning multiple values in Python is valid and very easy to understand.

Did you use Java or any other programming language before using Python? If yes, what happened when you tried to return multiple values in a function?

Yes! That gave you error. Java, C, C++ etc does not support multiple return values. You may come across various logic where you may incur the need to return multiple values for the proper functioning of the program. Thanks to Python!

How to return multiple values in Python function

Python provides the support of returning multiple values. These are the various ways to perform this task:

  1. Using Tuple

    def calc(a,b):
        c=a+b
        d=a*b
        return c,d
    ans1,ans2=calc(7,4)
    print(ans1,ans2)

    OUTPUT:

    11 28
  2. Using Object

    class Calculate:
        def calc(self,a,b):
            self.c=c
            self.d=d
            c=a+b
            d=a*b
            return c,d
    ans1,ans2=calc(7,4)
    print(ans1,ans2)

    OUTPUT:

    11 28
  3. Using List

    def calc(a,b):
        c=a+b
        d=a*b
        return [c,d]
    ans1,ans2=calc(7,4)
    list=calc()
    print(list)

    OUTPUT:

    11 28
  4. Using Dictionary

    def calc(a,b):
        dy=dict()
        dy['c']=a+b
        dy['d']=a*b
        return dy
    ans1,ans2=calc(7,4)
    dy=calc()
    print(dy)

    OUTPUT:

    11 28

S0, these are the following ways with the help of which you can return different and multiple values in Python. The values can differ in their datatype nature. For example, you can return a string and  a number together like this:

def func():
    str="Rachna"
    n=11
    return str,n
str, n = func() 
print(str) 
print(n)

This code will give no error and produce the following output:

Rachna
11

 

You may also read,

Find out the future date with Python

The simplest GUI using Python

Search a number in an array using Python

Leave a Reply

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