list.remove(): bug ??
chrismoll at chrismoll.homelinux.org
Wed Jun 11 20:34:47 CEST 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 )
> print i
> But the result is:
> 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,
More information about the Python-list