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

Duncan Booth duncan.booth at invalid.invalid
Tue Jan 29 15:17:42 EST 2008


Berteun Damman <berteun at NO_SPAMdds.nl> wrote:

> On Tue, 29 Jan 2008 09:23:16 -0800 (PST), attn.steven.kuo at gmail.com
><attn.steven.kuo at gmail.com> wrote:
>> If you're going to delete elements from
>> a list while iterating over it, then do
>> it in reverse order:
> 
> Why so hard? Reversing it that way creates a copy, so you might as
> well do:
>>>> a = [ 98, 99, 100 ]
>>>> for i, x in enumerate(a[:]):
>  ...     if x == 99: del(a[i])
>  ...     print x

Why so hard?

>>> a = [ 98, 99, 100, 98, 99, 100 ]
>>> for i, x in enumerate(a[:]):
        if x == 99: del(a[i])

        
>>> a
[98, 100, 98, 99]

oops! But:

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

        
>>> a
[98, 100, 98, 100]

Reversing it works. Your code doesn't.



More information about the Python-list mailing list