List problem

Reinhold Birkenfeld reinhold-birkenfeld-nospam at wolke7.net
Sun Oct 31 08:33:09 EST 2004


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]
       ^^^
What are these for?

Reinhold

-- 
[Windows ist wie] die Bahn: Man muss sich um nichts kuemmern, zahlt fuer
jede Kleinigkeit einen Aufpreis, der Service ist mies, Fremde koennen
jederzeit einsteigen, es ist unflexibel und zu allen anderen Verkehrs-
mitteln inkompatibel.               -- Florian Diesch in dcoulm



More information about the Python-list mailing list