list.remove(): bug ??

user at domain.invalid user at domain.invalid
Wed Jun 11 14:20:11 EDT 2003


Andrew Wilkinson wrote:
> 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

Very nice indeed, works as expected, that's all I needed !

thanks,
mathieu





More information about the Python-list mailing list