Why does Python skip elements when I modify a list while iterating over it?

This is a well-documented behaviour in Python, that you aren’t supposed to modify the list being iterated through. Try this instead:

for i in x[:]:
    x.remove(i)

The [:] returns a “slice” of x, which happens to contain all its elements, and is thus effectively a copy of x.

Leave a Comment