Why Deleting Items From a List While Looping Silently Skips Elements
items = [1, 2, 2, 3]for i in items: if i == 2: items.remove(i)print(items) # Expected: [1, 3] # Reality: [1, 2, 3] ← one '2' survives
No error. No warning. Just a bug that quietly ships to production because the output looks almost right.
Quick Summary
- Lists in Python are tracked internally by index, not by "the item you're currently looking at."
- When you remove an element, everything after it shifts one position to the left.
- The loop's internal pointer has already moved forward, so it ends up skipping the element that just slid into the gap.
- Two standard fixes: iterate in reverse index order, or build a new list instead of mutating the old one.
What's Actually Happening
A for loop over a list doesn't track "the current item." It tracks a position and an index and asks the list, "What's at this index now?" on every...
Copyright of this story solely belongs to hackernoon.com. To see the full text click HERE