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

Arnaud Delobelle arnodel at googlemail.com
Wed Jan 30 06:57:50 EST 2008


On Jan 29, 10:59 pm, Paul Hankin <paul.han... at gmail.com> wrote:
> 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]

Or one could use the trick of counting from the right (untested):

n = len(a)
for i, x in enumerate(a):
    if x == 99: del a[i-n]

--
Arnaud



More information about the Python-list mailing list