[New-bugs-announce] [issue16225] list.remove in for loop

Ian Carr-de Avelon report at bugs.python.org
Sun Oct 14 09:27:28 CEST 2012


New submission from Ian Carr-de Avelon:

I'm new to Python and I've hit what appears to me to be a bug, but may be a "feature", so a tutorial bug. 
I tried to loop through the items in a list, test each and remove those which fail the test.

Simplifying to illustrate:
>>> print test
[1, 2, 3, 4, 5]
>>> for item in test:
...     print item
...     test.remove(item)
... 
1
3
5
>>> print test
[2, 4]

Whereas I would expect to see all items looped through and non left in the list.
I have worked with languages where you are explicitly warned that you must not mess with the loop variable, or where the behaviour you will get is explained in detail, so you can use it. Not having anything flagged up in eg 5.6. Looping Techniques on
http://docs.python.org/tutorial/datastructures.html
I assumed that the behaviour would be safe and intuative.
Yours
Ian

----------
messages: 172855
nosy: Ian
priority: normal
severity: normal
status: open
title: list.remove in for loop
versions: Python 2.7

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


More information about the New-bugs-announce mailing list