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

attn.steven.kuo at gmail.com attn.steven.kuo at gmail.com
Tue Jan 29 12:23:16 EST 2008


On Jan 29, 8:34 am, William McBrine <wmcbr... at users.sf.net> wrote:
> 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
> ...
> 1
> 2
> 3
> 5
>
> >>> a
> [1, 2, 4, 5]
>
> Sure, the resulting list is correct. But 4 is never printed during the
> loop!
>
(snipped)


If you're going to delete elements from
a list while iterating over it, then do
it in reverse order:

>>> a = [ 98, 99, 100 ]
>>> last_idx = len(a) - 1
>>> for i, x in enumerate(a[::-1]):
...     if x == 99: del(a[last_idx - i])
...     print x
...
100
99
98
>>> a
[98, 100]

--
Hope this helps,
Steven




More information about the Python-list mailing list