MiddleDebuggingRareNot answered yet
Why does removing items while iterating skip elements?
This tries to drop even numbers, but silently skips some elements.
nums = [1, 2, 3, 4, 5, 6]
for n in nums:
if n % 2 == 0:
nums.remove(n)
print(nums)
Find and fix the bug.
Removing items during iteration shifts the indices under the iterator, so it skips elements. Never mutate a list while iterating it. Fix: iterate over a copy (for n in nums[:]:), or rebuild with a comprehension: nums = [n for n in nums if n % 2].
- ✗Assuming removal leaves the iterator aligned with the next element
- ✗Expecting a RuntimeError on
remove(that fires for size change, but indices still shift) - ✗Mutating the list in place instead of iterating a copy or rebuilding
- →Why does iterating over
nums[:]make the removal safe? - →How does a comprehension avoid mutating the list at all?