The Problem
Real data moment
Three real rows from the Chipotle dataset, all the same item:
order_id,quantity,item_name,item_price
2,2,Chicken Bowl,$16.98
3,1,Chicken Bowl,$10.98
7,1,Chicken Bowl,$11.25
A completely reasonable next question: what's the average price of a Chicken Bowl? Parsing was Lesson 01's problem. This lesson's problem is computing something real from correctly parsed data — and it turns out to hide its own trap.
The gotcha
item_price in this real dataset is the price for the entire line, not a single item — look again at the first row: quantity: 2, item_price: $16.98. That's the price for two bowls, not one. The loop above averaged three line totals together, two of which happen to be for a single bowl and one of which is for two — treating all three as directly comparable "a bowl costs this much" numbers, which they aren't.
rows = [
{"item_name": "Chicken Bowl", "quantity": 2, "item_price": 16.98},
{"item_name": "Chicken Bowl", "quantity": 1, "item_price": 10.98},
{"item_name": "Chicken Bowl", "quantity": 1, "item_price": 11.25},
]
total = 0
count = 0
for row in rows:
if row["item_name"] == "Chicken Bowl":
total += row["item_price"] / row["quantity"]
count += 1
average = total / count
print(round(average, 2))
10.24
$10.24, not $13.07 — a real, meaningful difference, not rounding noise. Dividing each row's price by its own quantity first gives the actual per-bowl price before averaging; skipping that step let one quantity: 2 row quietly drag the "average" upward by nearly 30%.
The loop was never the bug
Every line of the first version ran correctly, in the sense that Python executed exactly what was written, with no errors. The mistake was a silent assumption about what item_price means — that it's always a single-item price — made before writing a single line of the loop. No amount of loop-writing skill catches an assumption you didn't know you were making about the data itself.
Three real rows for a different item: (quantity=2, item_price=$2.18), (quantity=1, item_price=$1.09), (quantity=1, item_price=$1.09). A hand-written aggregation averages item_price directly, without dividing by quantity first. What average does it compute, and how does that compare to the true per-unit price?
(2.18 + 1.09 + 1.09) / 3 = 1.4533 — the naive average. The true per-unit price is exactly $1.09 (confirmed by 2.18 / 2 = 1.09 for the first row). The naive version overstates the price by about 33%, for exactly the same reason as Chicken Bowl: one line total for a quantity of 2 got averaged in as if it were a single-item price.