Efficient way to remove objects from a list

Peter Otten __peter__ at web.de
Mon Nov 3 08:34:07 EST 2008


M.-A. Lemburg wrote:

>> The typical way to do this is to iterate over the list in reverse
>> order and then using the item index as basis for removing the
>> item:
>> 
>> for i, item in enumerate(reversed(mylist)):
>>     # process item
>>     del mylist[i]
> 
> Sorry, the above should read:
> 
> for i, item in reversed(enumerate(mylist)):
>      # process item
>      del mylist[i]
> 

It's harder to get right than it might first appear:

>>> reversed(enumerate([]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: argument to reversed() must be a sequence

I think simplest approach is

for index in reversed(range(len(mylist))):
    item = mylist[index]
    ...

But I usually build a new list.

Peter




More information about the Python-list mailing list