tgoop.com/DataScience4/8835
Create:
Last Update:
Last Update:
✖️ MODIFYING A LIST WHILE LOOPING OVER IT SKIPS ITEMS.
Because of this, Python's iterator gets confused. When you remove an element, the next element shifts into its place, but the loop moves on to the next index, causing the shifted element to be skipped entirely.
The code looks logical, but the result is buggy — a classic iteration trap.
Correct — iterate over a copy* of the list, or build a new list.
Follow for more Python tips daily!
# hidden error — removing items while iterating skips elements
numbers = [1, 2, 3, 2, 4, 2, 5]
for num in numbers:
if num == 2:
numbers.remove(num) # seems like it should remove all 2s
# a '2' was skipped and remains in the list!
print(numbers) # [1, 3, 4, 2, 5]
# 🖕 correct version — iterate over a copy
numbers_fixed = [1, 2, 3, 2, 4, 2, 5]
# The [:] makes a crucial copy!
for num in numbers_fixed[:]:
if num == 2:
numbers_fixed.remove(num)
print(numbers_fixed) # [1, 3, 4, 5]
# A more Pythonic way is to use a list comprehension:
# [n for n in numbers if n != 2]
━━━━━━━━━━━━━━━
By: @DataScience4
