Efficient way to remove objects from a list

Chris Rebert clp at rebertia.com
Mon Nov 3 04:58:25 EST 2008


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

This way you aren't calling .remove() multiple times and only iterate
through the list once.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

>
> 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?
> --
> http://mail.python.org/mailman/listinfo/python-list
>


More information about the Python-list mailing list