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

Paul Hankin paul.hankin at gmail.com
Tue Jan 29 23:59:09 CET 2008


On Jan 29, 8:17 pm, Duncan Booth <duncan.bo... at invalid.invalid> wrote:
> Berteun Damman <berteun at NO_SPAMdds.nl> wrote:
> > On Tue, 29 Jan 2008 09:23:16 -0800 (PST), attn.steven.... at gmail.com
> ><attn.steven.... 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])

Why so hard? :)

a = [x for x in a if x != 99]

OK, so this doesn't modify a in place.. but how often do you really
need to do that?

If I really had to modify it in place (and the condition wasn't really
x == 99), how about:
bad_indices = [i for i, x in enumerate(a) if x == 99]
for bad_index in reversed(bad_indices):
    del a[bad_index]

--
Paul Hankin



More information about the Python-list mailing list