This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: remove() during iteration causes items to be skipped
Type: Stage:
Components: Interpreter Core Versions: Python 2.4
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: krabsa, rhettinger
Priority: normal Keywords:

Created on 2006-10-24 21:44 by krabsa, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (2)
msg30393 - (view) Author: Kevin Rabsatt (krabsa) Date: 2006-10-24 21:44
If, when iterating over the contents of a list, the
current item is removed, the next item is skipped.

#Code:
if __name__ == '__main__':
  items = [0,1,2,3,4,5]
  for i in items:
    print i
    items.remove(i)

#End Code

Outputs:
0
2
4

I believe the behavior is undesirable.  An argument can
be made to not fix, but the issue is worth noting.

msg30394 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2006-10-25 01:06
Logged In: YES 
user_id=80475

Sorry, this isn't a bug -- it is a natural side-effect of
mutating a object while iterating over it.  The various
approaches to dealing with this include:
* don't allow mutation while iterating -- dict.iterkeys()
uses this approach
* iterate over a copy of the object -- dict.keys() uses this
approach
* iterate over consecutive indices and ignore mutation --
lists use this approach

Programmers can avoid dealing with this issue by:

* precopying the list:
     for i in items[:]:
         print i
         remove(i)

* building a new list during iteration:
      items[:]  = [x for x in items if f(x)]

History
Date User Action Args
2022-04-11 14:56:20adminsetgithub: 44166
2006-10-24 21:44:32krabsacreate