Efficient way to remove objects from a list
Peter Otten
__peter__ at web.de
Mon Nov 3 08:38:26 EST 2008
Chris Rebert wrote:
> On Mon, Nov 3, 2008 at 1:40 AM, 一首诗 <newptcai at gmail.com> wrote:
>> Hi all,
>>
>> Today I wrote some code like this:
>>
>
> Build a new list as you go, then overwrite the old list with it.
>
> unfinished = []
>
>> for m in self.messages:
>> if not m.finished:
> unfinished.append(m)
>> continue
>>
>> #process the message
>>
>
> Remove the following code
>
>> fini = [m for m in self.messages if m.finished]
>> for m in fini:
>> self.messages.remove(m)
>
> self.messages[:] = unfinished
Just
self.messages = unfinished
if also OK unless you have multiple references to the self.messages list.
> This way you aren't calling .remove() multiple times and only iterate
> through the list once.
More information about the Python-list
mailing list