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
return lowest, highest, averagereturns one tuple with three items. The commas make the tuple; brackets are not needed.low, high, avg = ...is tuple unpacking. The number of names on the left must match the number of items, or Python raises aValueError.- If you do not unpack, you get the tuple itself:
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.