Sub topic 6
Returning several values at once
This chapter assumes you can define and call a function with def, and that you know how tuples and unpacking of lists work. It builds on the return statement from the earlier chapter.
One return, one object
A Python function returns exactly one object. When you write return a, b, Python builds a tuple from the two values and returns that tuple. The comma makes the tuple, not the parentheses.
def min_max(values):
return min(values), max(values)
low, high = min_max([3, 1, 4, 1, 5])
print(low, high) # 1 5The caller unpacks the tuple into two variables. Unpacking assigns the first item to low and the second to high, in order.
What the caller can do with the result
You do not have to unpack. You can keep the tuple whole and index it.
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'>
print(result[0]) # 1Unpacking rules
The number of names on the left must match the number of items in the tuple. A mismatch raises ValueError.
def min_max(values):
return min(values), max(values)
low, high, middle = min_max([3, 1, 4])This fails with ValueError: not enough values to unpack (expected 3, got 2).
Two techniques help when you only need part of the result:
- Use
_as a name for a value you do not need:low, _ = min_max(data). - Use a starred name to collect the rest:
first, *rest = some_function().
def stats(values):
return min(values), max(values), sum(values) / len(values)
low, _, mean = stats([2, 4, 6])
print(low, mean) # 2 4.0Returning a different number of values
Keep the shape of the result the same on every path. If one branch returns two values and another returns one, the caller cannot unpack safely.
def safe_min_max(values):
if not values:
return None, None
return min(values), max(values)
low, high = safe_min_max([])
print(low, high) # None NoneHere the empty case still returns two items, so low, high = ... works on every call. Returning a bare None for the empty case would make that unpacking fail with TypeError: cannot unpack non-iterable NoneType object.
When a tuple is not enough
A tuple identifies values only by position. With three or four values, callers must remember the order. Two alternatives make the result easier to read.
A dictionary names each value:
def describe(values):
return {"low": min(values), "high": max(values), "count": len(values)}
info = describe([3, 1, 4])
print(info["high"]) # 4A named tuple keeps tuple behavior and adds names:
from collections import namedtuple
Range = namedtuple("Range", ["low", "high"])
def min_max(values):
return Range(min(values), max(values))
r = min_max([3, 1, 4])
print(r.low, r.high) # 1 4
low, high = r
print(low, high) # 1 4A named tuple still unpacks like a plain tuple, so existing callers keep working.
Common errors
| Mistake | Result | Fix |
|---|---|---|
| Wrong number of names when unpacking | `ValueError` | Match the count, or use `_` or `*rest` |
| Returning one value on some paths and two on others | `TypeError` or `ValueError` in the caller | Return the same shape on every path |
| Printing the values instead of returning them | Caller receives `None` | Use `return` |
| Relying on position with many values | Values mixed up silently | Use a dictionary or named tuple |
Exercise
Write a function split_name(full_name) that takes a string such as "Ada Lovelace" and returns the first and last words as two values. What happens if the caller writes first, last, extra = split_name("Ada Lovelace")?
Show answer
Use parts = full_name.split() and return parts[0], parts[-1]. Calling split_name("Ada Lovelace") returns the tuple ("Ada", "Lovelace"). Unpacking it into three names raises ValueError: not enough values to unpack (expected 3, got 2), because the function returns exactly two items.
Exercise
A function divide(a, b) returns a // b, a % b. How would you keep only the remainder when calling it with 17 and 5?
Show answer
Write _, remainder = divide(17, 5). The underscore receives the quotient, which the code ignores, and remainder is 2.