Bugs item #1584028, was opened at 2006-10-24 16:44 Message generated for change (Comment added) made by rhettinger You can respond by visiting: https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1584028&group_id=5470
Please note that this message will contain a full copy of the comment thread, including the initial issue submission, for this request, not just the latest update. Category: Python Interpreter Core Group: Python 2.4 >Status: Closed >Resolution: Invalid Priority: 5 Private: No Submitted By: Kevin Rabsatt (krabsa) Assigned to: Nobody/Anonymous (nobody) Summary: remove() during iteration causes items to be skipped Initial Comment: 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. ---------------------------------------------------------------------- >Comment By: Raymond Hettinger (rhettinger) Date: 2006-10-24 20:06 Message: 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)] ---------------------------------------------------------------------- You can respond by visiting: https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1584028&group_id=5470 _______________________________________________ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com