list.remove(): bug ??

Jeremy Bowers jerf at jerf.org
Wed Jun 11 17:35:47 EDT 2003


On Wed, 11 Jun 2003 19:52:52 +0200, Mathieu Malaterre wrote:
> liste = ['foo1' , 'foo2', 'foo3', 'foo4', 'foo5' ]
> for i in liste:
>    if i == 'foo2':
>      liste.remove( i )
>    else:
>      print i

Metacomment: Others have already explained why this happens; I'd suggest
never, ever, ever doing this, not even a little. Modifying the list you're
currently iterating on is always prone to error, because it can be very
difficult to mentally model what's going on once the program gets any
larger then "trivial". (God help you if you start modifying the list
somewhere *other* then where you're currently iterating, or more then one
entry per loop...)

If you just mean to *skip* the 'foo2', you want (where I use "l" instead
of "liste", which is less prone to dropping the 'e' off th end ;-) ):

for i in l:
    if i != 'foo2':
       print i

If you mean to *remove* the foo2, what's probably best is

newlist = [x for x in l if x != 'foo2']

(Of course in this case it's obvious that l.remove('foo2') has identical
behavior if there's one and only one 'foo2' in l; I'm assuming you're
using 'foo2' as a placeholder for some sort of real condition.)

You don't really want to get into this habit, it'll bite hard someday. And
Python makes it so easy to do right... ;-)




More information about the Python-list mailing list