list.remove(): bug ??

Christian Kaenzig chrismoll at chrismoll.homelinux.org
Wed Jun 11 14:34:47 EDT 2003


On Wednesday 11 June 2003 19:52, 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' ??

By not modifying the list you are iterating over !

In your example, foo3 is not displayed because it takes the place of foo2 (2nd 
place) when it is removed. That way, the next element after foo2 is foo4 
(that is now on the 3rd place) and foo3 is skipped.

A simple way to iterate over a copy of the original list is:

for i in liste[:]:
    ...

I'm not a Python guru, so correct me if I'm wrong or incomplete.

Hope this helps,

Chris






More information about the Python-list mailing list