[docs] [issue16225] list.remove in for loop

Chris Jerdonek report at bugs.python.org
Sun Oct 14 21:38:42 CEST 2012


Chris Jerdonek added the comment:

> But in general the advice should be: if you want to insert or remove elements during iteration, iterate over a copy.

I would expand this to cover changing the list in any way.  I think the point being made is that iteration doesn't implicitly make a copy.  There are cases where modifying the list in place can also yield unexpected results.  For example (naive list reversal):

>>> words = ['cat', 'window', 'defenestrate']
>>> for i, word in enumerate(words):
...     words[-i-1] = word
... 
>>> words
['cat', 'window', 'cat']

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue16225>
_______________________________________


More information about the docs mailing list