Hone

Lessons · Python · changing a list while walking it

Do not change the list you are walking

Removing items from a list inside a for loop over that same list skips items, because removal shifts everything after it one place left.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Cleaning stale sessions, deleting matched rows, dropping bad readings: the natural first attempt is remove-inside-the-loop, and it quietly leaves some of the bad ones behind.

How to think about it

Build a new list of what you keep, or loop over a copy (items[:]) while removing from the original. Keeping is easier to reason about than deleting.

Worked example

items = [1, 2, 2, 3]
Two 2s to remove.
for x in items[:]:
Walk a copy.
    if x == 2:
Found one.
        items.remove(x)
Remove from the original.
print(items)
[1, 3]: both 2s gone.
kept = [x for x in [1, 2, 2, 3] if x != 2]
The cleaner way: keep what passes.
print(kept)
[1, 3].

Your turn

Drop every blank line.

lines = [ln for ln in lines if ln.()]

The trap

Deleting from a dict while iterating it raises RuntimeError outright. Lists fail silently, which is worse.

Practise changing a list while walking it on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.