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

Arnaud Delobelle arnodel at
Wed Jan 30 12:57:50 CET 2008

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


More information about the Python-list mailing list