Find the bug · #32 · Loops and closures Easy Python
Some expired items are never removed
A pantry app removes expired items every night, but leaves some behind.
On this page
The report
A pantry app removes expired items every night. Most nights it leaves some behind: when two expired items sit next to each other in the list, only the first one goes.
The code
Read it first: what should it do? Then click the line where you think the bug is.
def remove_expired(items, today):
"""Removes every item whose expiry day has passed."""
for item in items:
if item["expires"] < today:
items.remove(item)
return itemsRead it, then pick a line.
When you remove the item the loop is on, what happens to the item after it?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
pantry = [{"name": "milk", "expires": 1}, {"name": "bread", "expires": 2}, {"name": "jam", "expires": 9}]
print([i["name"] for i in remove_expired(pantry, today=5)])It prints
['bread', 'jam']
It should print
['jam']
Show the answer: the bug, the fix, and how you’d find it
The bug (lines 3, 5)
Lines 3 and 5 remove items from the same list the loop is walking through. When an item is removed, everything after it shifts one place left, but the loop still moves on to the next position, so the item that slid into the gap is never looked at. Build the filtered list instead of removing in place.
The fix
1def remove_expired(items, today):2 """Removes every item whose expiry day has passed."""3 for item in items:4 if item["expires"] < today:5 items.remove(item)3 items[:] = [item for item in items if item["expires"] >= today]6 return itemsHow you’d find it
- Reproduce with two expired items in a row: milk goes, bread stays.
- Trace the loop by position: it looks at index 0 (milk) and removes it; bread slides to index 0; the loop moves on to index 1, which is now jam. Bread was skipped.
- Changing a list while iterating over it is the cause, not the condition on line 4.
The test that catches it
It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.
items = [{"expires": 1}, {"expires": 1}, {"expires": 1}, {"expires": 9}]
assert remove_expired(items, 5) == [{"expires": 9}]Where else this bites
- Java throws
ConcurrentModificationExceptionfor the same thing (see the next drill). - JavaScript:
spliceinside a forward loop skips items; loop backwards or usefilter.