Python: Return Multiple Results from a Function (3 Ways)

Updated: July 10, 2023 By: Khue Post a comment

This concise, example-based article will walk you through 3 common approaches for returning multiple results from a function in Python. Without any further ado, let’s get started.

Using a Tuple

You can return multiple values as a tuple, which allows you to group multiple values into a single object. This technique is simple, straightforward, widely used, and suitable for returning a small number of results. It requires unpacking the tuple when calling the function.

Example:

def get_stats(numbers):
    min_val = min(numbers)
    max_val = max(numbers)
    avg_val = sum(numbers) / len(numbers)
    return min_val, max_val, avg_val

min_val, max_val, avg_val = get_stats([1, 2, 3, 4, 5])
print(f"Min: {min_val}, Max: {max_val}, Avg: {avg_val}")

Output:

Min: 1, Max: 5, Avg: 3.0

Using a List

In this method, we’ll return multiple values as a list, which allows for flexibility in adding or removing elements. It’s easy to manipulate the result list, suitable for returning a variable number of results.

Example:

def get_stats(numbers):
    min_val = min(numbers)
    max_val = max(numbers)
    avg_val = sum(numbers) / len(numbers)
    
    return [min_val, max_val, avg_val]

[min_val, max_val, avg_val] = get_stats([1, 2, 3, 4, 5])
print(f"Min: {min_val}, Max: {max_val}, Average: {avg_val}")

Another way to work with the returned values is to use indices like this:

def get_stats(numbers):
    min_val = min(numbers)
    max_val = max(numbers)
    avg_val = sum(numbers) / len(numbers)
    return [min_val, max_val, avg_val]

result = get_stats([1, 2, 3, 4, 5])
min_val = result[0]
max_val = result[1]
avg_val = result[2]

print(f"Min: {min_val}, Max: {max_val}, Average: {avg_val}")

Using a Dictionary

An alternative solution is to return multiple values as a dictionary. This way provides a named interface to access specific results, suitable for returning a set of related values. However, the code will be a little bit longer since it requires accessing elements by key when using the function’s result.

Example:

def get_stats(numbers):
    stats = {
        'min': min(numbers),
        'max': max(numbers),
        'avg': sum(numbers) / len(numbers)
    }
    return stats

result = get_stats([1, 2, 3, 4, 5])

min_val = result['min']
max_val = result['max']
avg_val = result['avg']

print(f"Min: {min_val}, Max: {max_val}, Avg: {avg_val}")