Sub topic 11
Returning Multiple Values and Unpacking Arguments
This chapter assumes you can define and call functions, know how packing and basic unpacking work (x, y = 3, 4), and have seen starred targets such as first, *rest = items. Here the same two ideas appear at function boundaries. A function hands several results back to its caller, and a caller spreads a collection into a function's parameters.
A function returns exactly one value
Python has no "multiple return values" feature. Every function returns one object. When you write return a, b, the comma builds a tuple, and that tuple is the one object returned. The parentheses are optional, as they are in any tuple expression.
def min_max(values):
return min(values), max(values)
result = min_max([3, 1, 4, 1, 5])
print(result)
print(type(result))
lo, hi = result
print(lo, hi)
lo, hi = min_max([3, 1, 4, 1, 5])
print(lo, hi)The first print shows (1, 5) and the second shows <class 'tuple'>. The last two lines are equivalent. Unpacking the call directly is the usual style, because the tuple never needs a name of its own.
Many built-ins work this way. divmod(17, 5) returns (3, 2), and dict.popitem() returns a (key, value) pair.
quotient, remainder = divmod(17, 5)
print(quotient, remainder)Choosing which results to keep
Unpacking requires a name for every item, unless you use a starred target. By convention, a throwaway name is spelled _. It is an ordinary variable, so nothing is discarded. The convention only tells readers that you do not use the value.
_, hi = min_max([3, 1, 4, 1, 5])
print(hi)
def parse_date(text):
year, month, day = text.split("-")
return int(year), int(month), int(day)
year, *_ = parse_date("2026-11-26")
print(year)Use *_ when you want the first few items and do not care how many follow. You can also skip the unpacking and index the result, as in min_max(values)[1]. Indexing is reasonable for a single value from a short tuple. Once you need two or more values, unpacking reads better.
Mismatched lengths
The length of the target list must match the length of the returned tuple, unless a starred target absorbs the difference.
def stats(values):
return min(values), max(values), sum(values) / len(values)
try:
lo, hi = stats([2, 4, 9])
except ValueError as e:
print(e)This prints too many values to unpack (expected 2). Too few names produce not enough values to unpack (expected 3, got 2) in the opposite case. Both are ValueError. They usually mean the function and its caller disagree about what is returned, for example after someone added a third result to the function.
Inconsistent return paths
A more subtle error appears when a function returns a tuple on one path and something else on another.
def find_range(values):
if not values:
return None
return min(values), max(values)
try:
lo, hi = find_range([])
except TypeError as e:
print(e)The message is cannot unpack non-iterable NoneType object. Because the unpacking happens in the caller, the traceback points at the call site, not at the early return. Two fixes work well:
- Make every path return the same shape, such as
return None, Noneorreturn 0, 0, when a placeholder is meaningful. - Raise an exception for the empty case instead, as
min([])itself does.
A function that sometimes returns a tuple and sometimes None forces every caller to check before unpacking. Avoid that design unless the "no result" case is expected and documented.
Unpacking arguments with `*` in a call
The * operator also works on the calling side. In a call, *sequence expands any iterable into separate positional arguments.
args = (2, 10)
print(pow(*args))
print(pow(2, 10))Both lines print 1024. This is the reverse of returning a tuple. A function returns one tuple that the caller splits, and a caller splits one tuple into the function's parameters.
You can mix starred and ordinary arguments, and use more than one star in a single call:
def describe(name, age, city="Oslo"):
return f"{name}, {age}, {city}"
person = ("Ada", 36)
print(describe(*person))
print(describe(*person, "Paris"))
print(describe("Grace", *[45, "Rome"]))
first = [1, 2]
second = [3, 4]
print(*first, *second, sep=" | ")The output is:
Ada, 36, Oslo
Ada, 36, Paris
Grace, 45, Rome
1 | 2 | 3 | 4Unpacking mappings with `**`
A dictionary can be spread into keyword arguments with **. The keys must be strings that match parameter names.
options = {"city": "Madrid"}
print(describe(*person, **options))This prints Ada, 36, Madrid. If a key does not match any parameter and the function has no **kwargs, Python raises TypeError: describe() got an unexpected keyword argument .... If the same parameter is supplied twice, for example describe(*person, name="X"), you get TypeError: describe() got multiple values for argument 'name'.
A useful idiom: transposing with `zip(*rows)`
Starring a list of rows passes each row to zip as a separate argument. zip then pairs up the first items, the second items, and so on.
matrix = [(1, 2, 3), (4, 5, 6)]
print(list(zip(*matrix)))
pairs = [("a", 1), ("b", 2), ("c", 3)]
letters, numbers = zip(*pairs)
print(letters, numbers)The first line prints [(1, 4), (2, 5), (3, 6)]. The second prints ('a', 'b', 'c') (1, 2, 3). This also shows the two directions working together: zip(*pairs) yields three tuples in a call, and the two-name assignment unpacks the result. Note that this only works if pairs is not empty. With an empty list, zip() yields nothing, and the two-name unpacking fails with not enough values to unpack (expected 2, got 0).
Evaluation happens before the call
* consumes the iterable entirely before the function runs. For a list or tuple this is invisible. For a generator or an iterator, the star exhausts it, so you cannot use it again afterward. A huge or infinite iterator will also use all your memory, or never finish.
numbers = iter([1, 2, 3])
print(*numbers)
print(list(numbers))The first line prints 1 2 3 and the second prints [], because the iterator is already used up.
The reverse side: `*args` in a definition
A definition uses the same symbol to collect arguments instead of spreading them. Inside the function, *numbers is a tuple of the extra positional arguments.
def total(*numbers):
print(type(numbers))
return sum(numbers)
print(total(1, 2, 3))
print(total(*range(5)))This prints <class 'tuple'> and 6, then another <class 'tuple'> and 10. The two uses of * mirror each other. In a definition it packs, and in a call it unpacks. A function written with *args that receives a starred call gets back the same items it was given.
| Position | Syntax | Effect |
|---|---|---|
| Assignment target | `a, *rest = items` | Collects leftover items into a list |
| Call | `f(*items)` | Spreads items into positional arguments |
| Call | `f(**mapping)` | Spreads items into keyword arguments |
| Definition | `def f(*args)` | Collects extra positional arguments into a tuple |
| Definition | `def f(**kwargs)` | Collects extra keyword arguments into a dict |
Note that a starred assignment target produces a list, while *args produces a tuple.
When a tuple stops being the right return type
Returning a bare tuple is fine for two or three values whose order is obvious, like (min, max) or (quotient, remainder). It gets worse as the tuple grows. Callers must remember what position 4 means, and adding a field breaks every caller that unpacks by position.
A named tuple fixes the readability problem and stays compatible with existing unpacking code:
from typing import NamedTuple
class Stats(NamedTuple):
low: int
high: int
mean: float
def summarize(values):
return Stats(min(values), max(values), sum(values) / len(values))
s = summarize([2, 4, 9])
print(s)
print(s.mean)
lo, hi, mean = s
print(lo, hi, mean)This prints Stats(low=2, high=9, mean=5.0), then 5.0, then 2 9 5.0. Callers can use names or positions, whichever suits them.
Use this rough guide when you design a return value:
- Two or three values with an obvious order: return a plain tuple.
- Several values, or values that callers often use selectively: return a named tuple.
- Values that must change after creation, or that carry behavior: use a dataclass or a class.
- A variable number of results: return a list, not a tuple, and document that.
Type hints help in the first case. def min_max(values: list[int]) -> tuple[int, int] tells readers and type checkers that the result has exactly two integers. Use tuple[int, ...] for a variable-length tuple of integers.
Summary of common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `ValueError: too many values to unpack` | The function returns more items than the caller has names | Match the names, or use `*rest` |
| `ValueError: not enough values to unpack` | The function returns fewer items than expected | Check every `return` path |
| `TypeError: cannot unpack non-iterable NoneType object` | A path returns `None` or has no `return` | Return a consistent shape, or raise |
| `TypeError: ... missing 1 required positional argument` | The starred sequence is too short for the call | Check the sequence length |
| Empty result after `print(*it)` | `*` exhausted an iterator | Convert to a list first if you need it twice |
Exercise
What does the following code print, and why? def f(): return 1, 2, 3 then a, *b = f() then print(a, b, type(b).__name__).
Show answer
It prints 1 [2, 3] list. The function returns the tuple (1, 2, 3). The starred target *b collects the remaining items, and a starred target always produces a list, even though the source is a tuple.
Exercise
A function split_name(full) returns (first, last) for names like "Ada Lovelace" but returns None for an empty string. The call first, last = split_name("") fails. Name the error, say why it appears at the call site, and give one way to fix the function.
Show answer
It raises TypeError: cannot unpack non-iterable NoneType object. The unpacking assignment runs in the caller, and None is not iterable. Fix the function by making every path return a two-item tuple, for example return "", "" for an empty string, or by raising ValueError for empty input so the caller never receives None.
Exercise
Given rows = [(1, "a"), (2, "b"), (3, "c")], write one assignment that produces numbers == (1, 2, 3) and letters == ("a", "b", "c"). What happens if rows is empty?
Show answer
numbers, letters = zip(*rows). The star spreads the rows into separate arguments to zip, which regroups the first items together and the second items together. If rows is empty, zip() yields nothing, so the assignment raises ValueError: not enough values to unpack (expected 2, got 0).