Re: List problem

From: Alex Martelli (aleaxit_at_yahoo.com)
Date: 10/31/04


Date: Sun, 31 Oct 2004 14:28:39 +0200

User <1@2.3> wrote:
   ...
> >In general, removing elements from a list while you're iterating though
> >the list is a bad idea. Perhaps a better solution is a list
> >comprehension:
>
> Unless you're using a while loop and iterating in reverse, for
> example:
>
> a = [0,1,2,3,4]
> pos_max = len(a) - 1 # Maximum iterable element
> pos = pos_max # Current element
> while pos >= 0:
> if a[pos] == 2:
> a.remove(2)
> pos_max = pos_max - 1
> pos = pos - 1

Still a bad idea.

    a[:] = [x for x in a if x != 2]

is more concise, idiomatic, and speedy. No reason to do low-level
twiddling with indices and fiddly loops, in cases where a list
comprehension can do the job so simply.

Alex