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

Paul Rubin http
Wed Jan 30 08:20:49 EST 2008


"Neil Cerutti" <mr.cerutti at gmail.com> writes:
> Or one can put on his bellbottoms, horn-rimmed glasses, and wear a mullet:
> 
> i = 0
> while i < len(a):
>   if a[i] == 99:
>     del a[i]
>   else:
>     i += 1

Quadratic time!! Yowch!!  Back to the future:

def rocket_science(xs):
   for x in xs:
      if x != 99:
         yield x

a[:] = list(rocket_science(a))

;-)



More information about the Python-list mailing list