Multiple Return Values
Concepts covered: Unpacking
A return statement hands back one value, and that value can hold several results. Writing return valid, rejected packs both into a tuple, an ordered group of values that cannot be changed after it is built. The caller takes the tuple apart with the same multiple assignment as a, b = 1, 2. One loop over the data can then report everything it counted, instead of 2 functions each walking the same rows.
def split_valid(amounts):
valid = 0
rejected = 0
for amount in amounts:
if amount > 0:
valid += 1
else:
rejected += 1
return valid, rejected
orders = [120, -5, 80, 0, 45]
result = split_valid(orders)
print(result)
good, bad = result
print("valid:", good)
print("rejected:", bad)(3, 2) valid: 3 rejected: 2
Step through it and watch result. The function sends back one object, (3, 2), and print shows it in parentheses because it is a tuple. The line good, bad = result then assigns by position: good gets the first slot and bad the second. Most code skips the middle name and unpacks straight from the call, as in good, bad = split_valid(orders).
- Separate count functions
- count_valid(orders) and count_rejected(orders) each loop over every row
- Each function repeats the same if amount > 0 test
- The 2 counts drift apart if one test is edited and the other is not
- One function returning a pair
- split_valid(orders) loops once and fills both counters
- The amount > 0 test is written once
- Valid plus rejected always equals the number of rows
The names must match the slots
Unpacking succeeds only when the left side has exactly one name per value. Here is what happens to the 2 values that split_valid(orders) returns:
| Left side | What happens |
|---|---|
| `good, bad =` | `good` is 3 and `bad` is 2 |
| `result =` | `result` holds the whole tuple `(3, 2)` |
| `good, bad, extra =` | `ValueError: not enough values to unpack (expected 3, got 2)` |
| `good =`, then `good + 1` | `TypeError: can only concatenate tuple (not "int") to tuple` |
The last row fails late. Storing the result in a single name works, and the error appears afterward, wherever the code expects a number. When a caller needs only some of the results, unpack the unwanted ones into _, an ordinary variable name that tells readers the value is ignored: good, _ = split_valid(orders). The _ still fills a slot, so the count must match.
Unpacking results inside a loop
Multiple return values fit pipeline loops well. Each call returns its pair, the loop unpacks it on the spot, and a running total collects one of the slots across batches:
def split_valid(amounts):
valid = 0
rejected = 0
for amount in amounts:
if amount > 0:
valid += 1
else:
rejected += 1
return valid, rejected
batches = {"mon": [120, -5, 80], "tue": [0, 0, 45], "wed": [60, 75]}
total_valid = 0
for day, amounts in batches.items():
valid, rejected = split_valid(amounts)
total_valid += valid
print(day, valid, rejected)
print("all valid:", total_valid)Output:
mon 2 1 tue 1 2 wed 2 0 all valid: 5
Every exit returns the same shape
An early exit can break callers. A bare return sends back None, and None has no slots to unpack. Predict the output:
What does this program print?
def to_fahrenheit(sensor, celsius):
if celsius < -273:
return
return sensor, celsius * 9 / 5 + 32
name, temp = to_fahrenheit("dock-4", 20)
print(name, temp)
name, temp = to_fahrenheit("dock-7", -300)
print(name, temp)- It prints dock-4 68.0, then None None for the rejected reading
- It prints dock-4 68, then raises TypeError: cannot unpack non-iterable NoneType object
- It raises TypeError: cannot unpack non-iterable NoneType object before printing anything
- It prints dock-4 68.0, then raises TypeError: cannot unpack non-iterable NoneType object
The fix gives every exit the same shape: each one returns 2 values, with None in the slot that has no answer. Callers can then unpack on every path and check that one slot:
def to_fahrenheit(sensor, celsius):
if celsius < -273:
return sensor, None
return sensor, celsius * 9 / 5 + 32
name, temp = to_fahrenheit("dock-7", -300)
if temp is None:
print(name, "reading rejected")Output:
dock-7 reading rejected
About this lesson
This section is part of the Functions: Intermediate lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.