← Back to Python, page 5

python-0082 · Easy fresher

Why does this loop that removes items from a list while iterating skip elements, and how is it fixed?

Removing an item shifts the following items left, while the loop's internal index still moves forward, so the item after each removed one is skipped. Build a new list with a comprehension, iterate over a copy, or loop backwards by index.

Full answer
python
nums = [2, 4, 5, 6, 8]
for n in nums:
    if n % 2 == 0:
        nums.remove(n)
print("buggy:", nums)

nums = [2, 4, 5, 6, 8]
print("fixed:", [n for n in nums if n % 2 != 0])

nums = [2, 4, 5, 6, 8]
for n in nums[:]:
    if n % 2 == 0:
        nums.remove(n)
print("copy:", nums)

Output:

text
buggy: [4, 5, 8]
fixed: [5]
copy: [5]

In the buggy loop, removing 2 moves 4 into position 0 while the loop moves on to position 1, which now holds 5, so 4 is never checked; the same happens with 6 and 8. The result still contains 4 and 8. The comprehension builds a new list and is the clearest fix; iterating over nums[:] also works because the copy does not change. Modifying a dict or set while iterating over it raises a RuntimeError instead of silently skipping.

python
nums = [2, 4, 5, 6, 8]
for n in nums:
    if n % 2 == 0:
        nums.remove(n)
print("buggy:", nums)

nums = [2, 4, 5, 6, 8]
print("fixed:", [n for n in nums if n % 2 != 0])

nums = [2, 4, 5, 6, 8]
for n in nums[:]:
    if n % 2 == 0:
        nums.remove(n)
print("copy:", nums)

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • Removal shifts later elements
  • The loop index still advances
  • Comprehensions build a new list safely
  • Iterate over a copy if mutating in place
  • Dicts and sets raise RuntimeError

Common mistakes

  • Mutating a list during iteration
  • Assuming the bug only affects consecutive matches

Follow-ups

  • How would you remove items in place efficiently?
  • What error does a dict give when changed during iteration?

Tips

  • Trace the indexes