List problem

Bengt Richter bokr at oz.net
Sun Oct 31 14:42:00 EST 2004


On Sun, 31 Oct 2004 14:28:39 +0200, aleaxit at yahoo.com (Alex Martelli) wrote:

>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.
>
Except maybe if the list is huge, and you don't want to generate a duplicate, e.g.,

 >>> a = [1,2,3,2,4,5]
 >>> a
 [1, 2, 3, 2, 4, 5]
 >>> i = 0
 >>> for x in a:
 ...     if x != 2:
 ...         a[i] = x
 ...         i += 1
 ...
 >>> del a[i:]
 >>> a
 [1, 3, 4, 5]

Should also be faster for large lists, IWT.

Regards,
Bengt Richter



More information about the Python-list mailing list