#32 · Loops and closures

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

Bug 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.

PythonClick the line you think is wrong
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 items

Read it, then pick a line.

What it prints

Running it on a small example prints the output on the left. It should print the output on the right.

The example
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 items

How you’d find it

  1. Reproduce with two expired items in a row: milk goes, bread stays.
  2. 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.
  3. 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 ConcurrentModificationException for the same thing (see the next drill).
  • JavaScript: splice inside a forward loop skips items; loop backwards or use filter.
Your progress stays on this device.