Efficient way to remove objects from a list

M.-A. Lemburg mal at egenix.com
Mon Nov 3 06:22:38 EST 2008


On 2008-11-03 12:12, M.-A. Lemburg wrote:
>> 一首诗 wrote:
>>> Hi all,
>>>
>>> Today I wrote some code like this:
>>>
>>>         for m in self.messages:
>>>             if not m.finished:
>>>                 continue
>>>
>>>             #process the message
>>>
>>>         fini = [m for m in self.messages if m.finished]
>>>         for m in fini:
>>>             self.messages.remove(m)
>>>
>>> As you can, I want to find these finished messages in
>>> "self.messages",
>>> process them, and then remove them from the list.
>>>
>>> Because a list can not be modified while iterating it,  I have to use
>>> a list "fini" to accomplish the target.
>>>
>>> I found a smell of bad performance here.
>>> Is there any faster ways?
> 
> 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]

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Nov 03 2008)
>>> Python/Zope Consulting and Support ...        http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ...             http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...        http://python.egenix.com/
________________________________________________________________________

:::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! ::::


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
    D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
           Registered at Amtsgericht Duesseldorf: HRB 46611



More information about the Python-list mailing list