Register Login

How to return multiple values in Python?

Returning multiple values at a time often saves a lot of time as the operation of multiple work within a block can be sent outside the scope for further work. Not all programming language support returning multiple values.

But Python does, which makes it stand out from the rest. This chapter will teach Python programmers how to return multiple values in Python. You as a Python programmer will learn the various techniques in detail how to implement them.

How to Return Multiple Values in Python?

We use functions to execute the tasks that can return a distinct value. However, in some use-cases, you'll have to pass two or more values outside the scope for further operations on the operated result. Other programming languages like C++ or Java will require an intricate process to achieve this.

Python can return more than two values simultaneously by following some handy methods. The methods are: using objects, using tuples, using a list, using a dictionary, and using data class. To get a clear understanding, refer to the examples.

Using Object

This process is quite similar to what we use in C/C++ and Java. The first step in 'Using Object' is to create a class. It holds multiple values along with returning an object of that particular class.

Program:

class Test:
    def __init__(self):
        self.str = "Hello World"
        self.x = 30   
  
def fun():
    return Test()
      
t = fun() 
print(t.str)
print(t.x)

Output:

Using Tuple

In Python, this method is one of the easiest methods to return multiple values. In this method, you need to separate the values by commas. To achieve this, we use Tuple.

Program:

# Returning Multiple Values using Tuples 
def multiple(): 
operation = "Sum" 
total = 2+7
return operation, total; 
operation, total = multiple() 
	print(operation, total)

Output:

Using a List

Similar to the previous methods, we can also use Python lists to return multiple values. Lists are a collection of objects. A lot of people confuse it with arrays. However, we use lists to store the items of different data types. We can also add values to the list and return them.

Program:

#Returning Multiple Values using List 
def multiple(): 
operation = "Sum" 
total = 2+7
return [operation, total]; 

values = multiple() 
print(values)

Output:

Using a Dictionary

In the method where we use lists, we cannot extract a particular value easily. So, we will have to follow intricate procedures. It is where the dictionary comes to our rescue. In this method, you can use keywords for names to access information.

Program:

#Returning Multiple Values using Dictionary
def multiple():
    values = dict();
    values['operation'] = "Sum" 
    values['total'] = 2+7
    return values;

values = multiple()

print(values)

Output:

Using Data Class:

We can use Data Class in Python version 3.7 and above. Not only does it return a class, but it also adds unique methods. The module consists of a decorator along with functions. It helps to add some unique ways automatically.

Program:

#Returning Multiple Values using Data Classes
from dataclasses import dataclass
@dataclass
class multiplevalues():
    operation: str
    num1: int = 0
    num2: int = 0
    def values(self) -> float:
        return self.num1 + self.num2   
# passing arguments into the Data Class 
all_values = multiplevalues("Addition", 5, 10)
v = all_values.values() 

print(v)
print(all_values)

Output:

Limitations and challenges of Returning Multiple Values using Python:

  1. We use the tuple and objects method extensively. However, one should take extra precautions while using it. If these functions do not have the proper names or do not use the proper name to identify the values, it an ultimately generates an error.
  2. The sole difference between the list method and the tuple method is that lists are mutable.
  3. We use the dictionary method in cases where we want to return multiple values in pairs, but keeping track of the naming becomes hard.
  4. The data class method is quite complex. Initially, you might find it difficult to understand. Hence, you should try out the other ways and choose this option only when you have no alternatives.

Conclusion

Some programming languages like C, C++ do not allow multiple returns through normal procedures. Compared to other programming languages, it is easier to return multiple values in Python. Most people use the first three methods. However, one should take extra precautions as it generates an error in some cases.

The data class method is the least used as it is complex to understand and everyone do not use the object-oriented concept. Also, it is slower and less efficient compared to others. However, if you are confident enough, you can use the data class method.