A common pitfall for Python beginners is modifying a list while iterating over it. This can lead to skipped elements, unexpected behavior, or even runtime errors.
Consider this example:
items = [1, 2, 2, 3, 4]
for item in items:
if item == 2:
items.remove(item)
print(items)
The expected output is [1, 3, 4], but the actual output is [1, 2, 3, 4]. The second 2 remains because removing an element shifts the remaining ones, causing the iterator to skip the next element.
To fix this, iterate over a copy of the list:
for item in items[:]:
if item == 2:
items.remove(item)
print(items)
Alternatively, use a list comprehension for cleaner code:
items = [x for x in items if x != 2]
Rule of thumb: Never modify a collection while iterating over it. Always work on a copy or use a comprehension.