DEV Community

Cover image for Never Remove Items From a List While Looping Over It (Python)
Muiduzzaman Lipu for Refactorly

Posted on

Never Remove Items From a List While Looping Over It (Python)

I asked Python to remove every even number from a list:

nums = [2, 2, 3, 4]
for n in nums:
    if n % 2 == 0:
        nums.remove(n)

print(nums)   # [2, 3]
Enter fullscreen mode Exit fullscreen mode

One 2 survived. No error, no warning, just a wrong answer. Below is exactly why, the same bug with dictionaries, and four ways to do it right. Everything was run on Python 3.15.

Video version:

Why: the loop walks by index

A for loop over a list keeps an internal position: index 0, then 1, then 2… remove() shifts every later item one step to the left. I printed each step:

visit index 0 → 2   list [2, 2, 3, 4]   remove it
visit index 1 → 3   list [2, 3, 4]      (the second 2 slid to index 0)
visit index 2 → 4   list [2, 3, 4]      remove it
done                list [2, 3]
Enter fullscreen mode Exit fullscreen mode

After the first removal, the second 2 moves into index 0, a position the loop has already passed. It's never visited.

Why tests don't catch it

It only goes wrong when two matching items are next to each other:

# remove evens from [1, 2, 4, 6, 7]  →  [1, 4, 7]   (4 survived)
# remove evens from [1, 2, 3, 4, 5]  →  [1, 3, 5]   (correct, by luck)
Enter fullscreen mode Exit fullscreen mode

If your test data alternates, the bug passes every test.

Fix 1 (best): build a new list

nums = [n for n in nums if n % 2 != 0]   # [3]
Enter fullscreen mode Exit fullscreen mode

Don't modify, filter. It's one line, easy to read, and faster than repeated remove() calls (each remove() scans and shifts the list).

Fix 2: loop over a copy, or replace in place

If other code holds a reference to the same list object and you need to change that object:

for n in nums[:]:            # nums[:] is a copy
    if n % 2 == 0:
        nums.remove(n)

# or replace the contents of the same object
nums[:] = [n for n in nums if n % 2 != 0]
Enter fullscreen mode Exit fullscreen mode

Both give [3].

Fix 3: index loops must go backwards

A forward range(len(...)) loop doesn't skip. It crashes, because range was computed before the list shrank:

for i in range(len(nums)):
    if nums[i] % 2 == 0:
        nums.pop(i)
# IndexError: list index out of range
Enter fullscreen mode Exit fullscreen mode

Looping backwards is safe, because removing from the end never moves items you haven't visited yet:

for i in range(len(nums) - 1, -1, -1):
    if nums[i] % 2 == 0:
        del nums[i]
# [3]
Enter fullscreen mode Exit fullscreen mode

Dicts and sets: at least they crash

users = {"ana": "active", "ben": "banned", "chen": "banned"}
for name, status in users.items():
    if status == "banned":
        del users[name]
# RuntimeError: dictionary changed size during iteration
Enter fullscreen mode Exit fullscreen mode

Sets raise RuntimeError: Set changed size during iteration. Same fixes:

for name in list(users):                 # loop over a copy of the keys
    if users[name] == "banned":
        del users[name]

users = {k: v for k, v in users.items() if v != "banned"}   # or rebuild
# {'ana': 'active'}
Enter fullscreen mode Exit fullscreen mode

Cheat sheet

  • Never add or remove items in the list you're looping over.
  • Best: [x for x in items if keep(x)].
  • Same object needed? for x in items[:] or items[:] = [...].
  • Index loop? Go backwards.
  • Dict/set: for k in list(d) or a comprehension.
  • Test with matching items next to each other.

Have you shipped this one? 👇


I post one tested coding tip every day on YouTube at Refactorly. The 30-second version of this one is here.

Top comments (0)