Multiple Return Values in Python Functions

Introduction

While functions typically return a single value or no value at all, there are cases in which having multiple return values in Python functions is desirable. It is a general programming best-practice to have each function be responsible for doing one thing only, and therefore those multiple returned values should be closely related to a single concept.

Syntax for Returning Multiple Values

Python offers a convenient syntax for returning multiple values from a function. By simply separating the values with commas after the `return` keyword, you can create a collection of values that are returned as a cohesive entity.

Example:

def get_personal_info():
    name = "Alice"
    age = 30
    return name, age
    
result = get_personal_info()
print(result)

Output:

('Alice', 30)

The returned value is actually a Python tuple containing the name and age. In the example, this tuple is assigned to the variable result.

Unpacking Returned Values

To work with the individual values returned from a function, you can use a technique called unpacking. Unpacking allows you to easily assign the elements of a tuple (or any iterable) to separate variables.

Example:

name, age = get_personal_info()
print(f"Name: {name}, Age: {age}")

Output:

Name: Alice, Age: 30

Here, the values returned by the get_personal_info() function are unpacked into the variables name and age, which are then used to create a formatted message.

Use Cases for Multiple Return Values

Use Case 1: Mean, Median, and Mode Statistics

Consider a scenario where you’re working on a data analysis project and frequently need to compute statistics like mean, median, and mode for a given list of numbers. Python’s statistics module provides functions to calculate these statistics.

Example:

import statistics as stat

data = [2, 3, 3, 5, 5, 7, 7, 7, 8, 9]

mean = stat.mean(data)
median = stat.median(data)
mode = stat.mode(data)

print("Mean:", mean)
print("Median:", median)
print("Mode:", mode)

Output:

Mean: 5.6
Median: 6.0
Mode: 7

Instead of repeatedly calling the mean, median, and mode, you can encapsulate all three computations inside a function called calculate_stats:

def calculate_stats(numbers):
    mean = statistics.mean(numbers)
    median = statistics.median(numbers)
    mode = statistics.mode(numbers)
    return mean, median, mode

This function returns all three statistics using the multiple-return-value syntax. Notice that the function adheres to best-practices by having return values that are all closely related and aligned under the single concept of “stats”.

With the calculate_stats() function in place, the earlier example can be restructured as follows:

import statistics as stat

data = [2, 3, 3, 5, 5, 7, 7, 7, 8, 9]

mean, median, mode = calculate_stats(data)

print("Mean:", mean)
print("Median:", median)
print("Mode:", mode)

Use Case 2: Splitting a List

Suppose you’d like to write a function that splits a list into two sub-lists, given a certain ratio of split. The function will return two values, one for each of the sub-lists.

Example:

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
split1, split2 = split_list(lst, 0.8)

print(split1)
print(split2)

Output:

[1, 2, 3, 4, 5, 6, 7, 8]
[9, 10]

In the example above, the original list, lst, is [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. The split_list() function splits the list into two new sub-lists and returns them. The first sub-list is the initial 0.8 (i.e. 80%) of the original list, and the second is the remaining 0.2 (i.e. 20%).

split_list() returns both sub-lists at once. This is convenient because you can assign both sub-lists to separate variables, as the example does with variables split1 and split2, using one function call.

The following code is the implementation of split_list(). How it actually does the split is not important to this lesson. (It does it with slicing syntax.) What is important is the last line of the function, which returns both sub-lists.

def split_list(lst, split_ratio):
    split_loc = round(len(lst) * split_ratio)
    split1 = lst[:split_loc]
    split2 = lst[split_loc:]

    return split1, split2

Summary & Reference for Multiple Return Values in Python Functions

Returning multiple values from Python functions allows for encapsulating related information in a cohesive manner. While functions are usually designed to return a single value, there are scenarios where multiple values are useful.


Python offers a straightforward syntax for this purpose, where multiple values are separated by commas after the return keyword.

def get_personal_info():
    name = "Alice"
    age = 30
    return name, age

The values returned from the function are in the form of a tuple, but they can be unpacked into individual variables using a simple assignment statement.

name, age = get_personal_info()