list.remove(): bug ??
Andrew Wilkinson
ajw126 at NOSPAMyork.ac.uk
Wed Jun 11 14:16:24 EDT 2003
Mathieu Malaterre wrote:
> Hi all,
>
> here is a very simple script:
>
> liste = ['foo1' , 'foo2', 'foo3', 'foo4', 'foo5' ]
> for i in liste:
> if i == 'foo2':
> liste.remove( i )
> else:
> print i
>
>
> But the result is:
>
> foo1
> foo4
> foo5
>
> How should I do to still print 'foo3' ??
>
> thanks a lot,
> mathieu
The problem is that you're modifying the list that you're iterating over.
The simplest method to correct this is to take a copy of the list and
iterate over it instead of the actual list.
liste = ['foo1' , 'foo2', 'foo3', 'foo4', 'foo5' ]
for i in liste[:]:
if i == 'foo2':
liste.remove( i )
else:
print i
The above code works as expected. I don't see this as a bug, although its
perhaps not as intuitive as you would expect from Python.
Hope this help,
Andrew Wilkinson
More information about the Python-list
mailing list