How do I Return Multiple Values From a Function?

[toc]

Problem Statement: How to return multiple values from a given function in Python?

Functions are used to break the program into smaller chunks. As the program grows larger, functions make it more organized. In Python, functions are generally used for performing a specific task that involves returning a particular value. But in some cases, we may have to return more than two values. In programming languages other than Python, the code that returns two values becomes quite complex to write. However, in Python, few methods can be used to return multiple values from a function with ease. Some of these methods use a collection data type in Python to return the multiple values. Let’s have a close look at all of these data types.

Method 1- Using Python Lists

In Python, lists are a collection of items that are used to store multiple items in a single variable. They are similar to arrays, with the difference being that lists can store values of various data types. Lists can be modified, i.e., they are mutable. We can even add and remove items from the list after it has been created. We can use this property of lists to return multiple values. Please follow the example given below.

Example:

# Using a list to return multiple values
def add(a, b):
    s = a + b
    op = "Addition"
    # Returning multiple values
    return [op, s]


def subs(a, b):
    s = a - b
    op = "Subtraction"
    return [op, s]


a = 10
b = 5
x = add(a, b)
y = subs(a, b)

# Printing the list values
print(x)
print(y)
print("The type of the data structure used to return multiple values:", type(x))

Output:

['Addition', 15]
['Subtraction', 5]
The type of the data structure used to return multiple values: <class 'list'>

Method 2- Using Tuples (Comma Separated Values)

In Python, we can return multiple values from a function by simply separating them by commas. We just need to write each value after the return, separated by commas. In Python, these comma-separated values are known as tuples. A tuple is a collection of items that are ordered and cannot be changed. It is used to store multiple items in a single variable.

Example:

# Using commas to return multiple values
def add(a, b):
    s = a + b
    op = "Addition"
    # Returning multiple values
    return op, s


def subs(a, b):
    s = a - b
    op = "Subtraction"
    return op, s


a = 10
b = 5
x = add(a, b)
y = subs(a, b)

# Printing the tuple values
print(x)
print(y)
print("The type of the data structure used to return multiple values:", type(x))

Output:

('Addition', 15)
('Subtraction', 5)
The type of the data structure used to return multiple values: <class 'tuple'>

Method 3- Using A Dictionary

Dictionaries are data structures in Python that store the data in the form of key-value pairs. It is a collection of ordered items that can be changed. However, the dictionary does not allow duplicates.  It is easier to return multiple values from a function using the dictionary as we can use the relevant key names, and the values can be accessed easily.

# Using a dictionary to return multiple values
def add(a, b):
    x = dict()
    x['op'] = "Addition"
    x['s'] = a + b
    # Returning multiple values
    return x


def subs(a, b):
    y = dict()
    y['op'] = "Subtraction"
    y['s'] = a - b
    # Returning multiple values
    return y


a = 10
b = 5
x = add(a, b)
y = subs(a, b)

# Printing the values
print(x)
print(y)
print("The type of the data structure used to return multiple values:", type(x))

Output:

{'op': 'Addition', 's': 15}
{'op': 'Subtraction', 's': 5}
The type of the data structure used to return multiple values: <class 'dict'>

Method 4- Using a Python Data Class

We can use the Data Classes in Python to return multiple values from a function. In Python, data classes are a method of adding specific methods to the user-defined class. However, ensure that you are using Python version 3.7 or higher while using this approach to return multiple values from a function.

Example:

# Using data class to return multiple values
from dataclasses import dataclass


@dataclass
class Multi:
    y0: int
    y1: float
    y2: int

    def cost(self, x):
        y0 = x + 10
        y1 = x * 30
        y2 = y0 * self.y2
        return Multi(y0, y1, y2)


# Passing the arguments into the Data Class
s = Multi(25, 10, 5)
obj = s.cost(100)
print(obj.y0)
print(obj.y1)
print(obj.y2)

Output:

110
3000
550

Method 5- Using Generator

We can use the generator to return multiple values from a function in Python. However, the generator often yields the value one by one. Hence, this method is not recommended to be used when you have to return a huge number of values as using the method to yield the numbers may consume lots of system resources.

Quick overview of yield:
Instead of using the return keyword in Python, we can use the yield keyword to return the value.  But the yield keyword only pauses the function, it does not terminate it.  The current state gets saved on the stack and further, it returns the yielded value. If there are no more values to yield in the function, and the yield keyword is used, the StopIteration error is raised.

Example:

# Using a generator to return multiple values
def add_mul(a, b):
    s = a + b
    op = a*b
    # Returning multiple values
    yield s
    yield op


def sub_div(a, b):
    s = a - b
    op = a/b
    # Returning multiple values
    yield s
    yield op


a = 10
b = 5
x = add_mul(a, b)
y = sub_div(a, b)

s1 = next(x)
print("Addition: ", s1)
op1 = next(x)
print("Multiplication: ", op1)
s1 = next(y)
print("Subtraction: ", s1)
op1 = next(y)
print("Division: ", op1)

Output:

Addition:  15
Multiplication:  50
Subtraction:  5
Division:  2.0

Recommended: Yield Keyword in Python – A Simple Illustrated Guide

Conclusion

That is all the methods to return multiple values from a given function in Python. I hope you found it helpful. Please stay tuned and subscribe for more such interesting tutorials in the future. Happy learning!

Authors: Rashi Agarwal and Shubham Sayon