Sub topic 6
Returning Several Values at Once
This chapter assumes you can define a function with def, use return to send one value back, and call functions with positional arguments. You should also know what a tuple is and that tuples are immutable sequences. Here you will see what Python does when a function returns several values, how callers take those values apart, and when a tuple stops being the right container.
One return statement, one object
Python functions return exactly one object. When you write several values after return, separated by commas, Python packs them into a single tuple and returns that.
def min_max(values):
return min(values), max(values)
result = min_max([3, 1, 4, 1, 5])
print(result) # (1, 5)
print(type(result)) # <class 'tuple'>The parentheses are optional. The comma creates the tuple, not the parentheses. return min(values), max(values) and return (min(values), max(values)) do the same thing. Most Python code leaves the parentheses out for short returns and adds them when the line gets long or when it helps readability.
This means there is no special "multiple return" feature in the language. It is ordinary tuple creation combined with a feature on the calling side called unpacking.
Unpacking at the call site
Unpacking assigns the items of a sequence to several names in one statement. The number of names on the left must match the number of items on the right.
def min_max(values):
return min(values), max(values)
low, high = min_max([3, 1, 4, 1, 5])
print(low, high) # 1 5The function and the caller agree on the order of the values. Nothing in the language checks that agreement beyond the count, so high, low = min_max(...) runs without error and silently swaps the meaning of the two names.
When the count does not match
If the numbers differ, Python raises a ValueError at the line that unpacks.
def min_max(values):
return min(values), max(values)
try:
a, b, c = min_max([3, 1, 4])
except ValueError as error:
print(error) # not enough values to unpack (expected 3, got 2)
try:
(only,) = min_max([3, 1, 4])
except ValueError as error:
print(error) # too many values to unpack (expected 1)The error is reported where the caller unpacks, not where the function returns. When you see this message, check the return statement of the function you called.
Ignoring and collecting values
By convention, the name _ marks a value you do not need. A starred name collects the leftover items into a list.
def stats(values):
ordered = sorted(values)
return ordered[0], ordered[-1], sum(ordered) / len(ordered)
low, high, _ = stats([2, 4, 9])
print(low, high) # 2 9
first, *rest = stats([2, 4, 9])
print(first) # 2
print(rest) # [9, 5.0]Only one starred name is allowed per unpacking target. The starred name always receives a list, even when it collects zero items.
Keeping the tuple
You do not have to unpack. If you assign the result to a single name, you keep the tuple and can index it.
def stats(values):
ordered = sorted(values)
return ordered[0], ordered[-1], sum(ordered) / len(ordered)
summary = stats([2, 4, 9])
print(summary[0]) # 2
print(summary[-1]) # 5.0
print(len(summary)) # 3Indexing by position is fragile for results with more than two or three items, because the reader has to remember what summary[2] means.
Single-item tuples and a common trap
A tuple with one item needs a trailing comma. Without the comma, parentheses only group an expression, and you get the bare value.
def with_comma():
return 1,
def without_comma():
return (1)
print(with_comma()) # (1,)
print(without_comma()) # 1This matters when a function sometimes returns one item and sometimes several. Callers that unpack will break on the single-item case, so design the function to return the same shape every time.
Keep the shape consistent
A function should return the same number and kind of values on every path. The most common bug is returning None on a failure path while returning a tuple on success.
def bad_divide(a, b):
if b == 0:
return None
return a // b, a % b
try:
quotient, remainder = bad_divide(7, 0)
except TypeError as error:
print(error) # cannot unpack non-iterable NoneType objectThe caller cannot tell that the failure came from the function, and the error message points at the unpacking line. Raise an exception for the error case instead.
def safe_divmod(a, b):
if b == 0:
raise ValueError("b must not be zero")
return a // b, a % b
quotient, remainder = safe_divmod(17, 5)
print(quotient, remainder) # 3 2If a missing result is a normal outcome rather than an error, return a single optional value instead of an optional tuple. Another option is to return a tuple that always has the same length, with a flag such as (found, value). Pick one convention and document it.
Choosing a container for the results
A tuple is the lightest way to return several values, but it is not the only one. The right choice depends on how many values there are and how the caller uses them.
| Container | Access | Mutable | Best for |
|---|---|---|---|
| Tuple | By position, unpacking | No | Two or three values with an obvious order, such as `(low, high)` |
| `NamedTuple` | By name, position, unpacking | No | Several values that callers read by name but may also unpack |
| Dictionary | By key | Yes | Results with optional or variable fields, or results passed on as JSON |
| Dataclass | By attribute | Yes by default | Results that carry behavior or that callers may update |
| List | By position | Yes | Many values of the same kind, not a fixed set of different ones |
A NamedTuple is a good upgrade when a tuple grows beyond about three items. It is still a tuple, so existing code that unpacks the result keeps working.
from typing import NamedTuple
class Stats(NamedTuple):
low: float
high: float
mean: float
def describe(values: list[float]) -> Stats:
return Stats(min(values), max(values), sum(values) / len(values))
stats = describe([2.0, 4.0, 9.0])
print(stats) # Stats(low=2.0, high=9.0, mean=5.0)
print(stats.mean) # 5.0
low, high, mean = stats
print(low, high) # 2.0 9.0Returning a dictionary works, but it moves mistakes from import time to run time. A misspelled key such as result["hihg"] fails only when that line runs, and tools cannot check it ahead of time.
Type hints for several return values
The hint for a fixed-length tuple lists the type of each position, in order.
def min_max(values: list[int]) -> tuple[int, int]:
return min(values), max(values)
def split_name(full_name: str) -> tuple[str, str]:
first, _, last = full_name.partition(" ")
return first, last
print(min_max([3, 1, 4])) # (1, 4)
print(split_name("Ada Lovelace")) # ('Ada', 'Lovelace')The hint tuple[int, ...] means a tuple of any length whose items are all int. Use it when the length varies. Use tuple[int, int] only when the length is always two. A type checker such as mypy reads these hints and reports a wrong unpack count before the program runs, but Python itself does not enforce them.
Edge cases and common mistakes
- Returning inside a loop. A
returnends the function on its first execution. If you want to collect many results, build a list in the loop and return it after the loop. - Printing instead of returning.
print(low, high)inside the function shows values on screen but the caller receivesNone. See the earlier chapter on the implicitNone. - Operator precedence. In
return a, b + 1the tuple is(a, b + 1), not(a, b) + 1. Add parentheses if you are unsure. - Order mismatches. Unpacking by position means swapping two names compiles and runs. Tests that check both values catch this.
- Mutable items inside the tuple. A tuple cannot change which objects it holds, but a list inside it can still be modified.
return [1], [2]gives the caller two lists they can change. - Too many values. If a function returns five or six items, the call site becomes hard to read and easy to get wrong. That is a sign the values belong together in one named object.
- Chained unpacking of nested results. Nested structures can be unpacked directly, as in
(low, high), count = bounds_and_count(data), but only do this when the nesting is simple.
The last pattern is easy to demonstrate.
def bounds_and_count(values):
return (min(values), max(values)), len(values)
(low, high), count = bounds_and_count([5, 2, 8])
print(low, high, count) # 2 8 3Quick checklist
- Does every path through the function return the same number of values?
- Does the function name or docstring make the order of the values clear?
- Are there more than three values? If so, consider a
NamedTupleor dataclass. - Is the error case handled with an exception rather than a different return shape?
- Does the type hint spell out each position, such as
tuple[int, int]?
Exercise
What does type(f()) print for def f(): return 1, 2, and what does a, b, c = f() do?
Show answer
type(f()) prints <class 'tuple'>, because the comma in the return statement builds a tuple. The line a, b, c = f() raises ValueError: not enough values to unpack (expected 3, got 2), because the function returns two items and the target has three names.
Exercise
Write a function first_last(text) that returns the first and last characters of a non-empty string, and explain what a caller gets from result = first_last("python").
Show answer
Use def first_last(text): return text[0], text[-1]. The call first_last("python") returns the tuple ('p', 'n'), so result holds that tuple. The caller can also write first, last = first_last("python") to get 'p' and 'n' as separate names.
Exercise
A function returns None when its input is invalid and (count, total) otherwise. Why does count, total = f(bad_input) fail, and how would you fix the function?
Show answer
Unpacking None raises TypeError: cannot unpack non-iterable NoneType object, because None is not a sequence. Fix it by raising an exception such as ValueError for invalid input, so the function always returns a two-item tuple when it returns at all. The caller can then wrap the call in try and except when failure is possible.