PythonMastery
Python programs · Functions · beginner

Return multiple values from a function in Python

Return several values from one function by separating them with commas. Python packs them into a tuple, and you unpack them into separate variables.

A Python function can return several values at once. Write them after return separated by commas, and unpack them into separate variables when you call the function.

The program

python
def stats(numbers):
    lowest = min(numbers)
    highest = max(numbers)
    average = sum(numbers) / len(numbers)
    return lowest, highest, average

low, high, avg = stats([12, 45, 7, 30, 21])
print(f"Min: {low}, Max: {high}, Average: {avg}")
output
Min: 7, Max: 45, Average: 23.0

How it works

python
def stats(numbers):
    return min(numbers), max(numbers), sum(numbers) / len(numbers)

result = stats([12, 45, 7, 30, 21])
print(result)
print(type(result))
output
(7, 45, 23.0)
<class 'tuple'>

An empty list

min() of an empty list raises a ValueError, and len() would be 0 in the division. Check for that case first and return a clear result:

python
def stats(numbers):
    if not numbers:
        return None, None, None
    return min(numbers), max(numbers), sum(numbers) / len(numbers)

print(stats([]))
print(stats([5]))
output
(None, None, None)
(5, 5, 5.0)

When a function returns many values, or the order is easy to forget, a dictionary or a dataclass with named fields is easier to read than a long tuple.

Learn the idea: Functions & Scoping, Tuples: Lists That Can't Be Changed