Removal of element from list while traversing causes the next element to be skipped

Santiago Romero sromero at gmail.com
Tue Jan 29 18:51:19 CET 2008


> Look at this -- from Python 2.5.1:
>
> >>> a = [1, 2, 3, 4, 5]
> >>> for x in a:
> ...     if x == 3:
> ...         a.remove(x)
> ...     print x

 Well ... you could use:

>>> for i in range(len(a)-1, -1, -1):
...    print a[i]
...    if a[i] == 3: del a[i]
...
5
4
3
2
1
>>> print a
[1, 2, 4, 5]


 Bye.



More information about the Python-list mailing list