List problem

Alex Martelli aleaxit at yahoo.com
Sun Oct 31 07:28:39 EST 2004


User <1 at 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



More information about the Python-list mailing list