Efficient way to remove objects from a list

一首诗 newptcai at gmail.com
Mon Nov 3 04:40:38 EST 2008


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?



More information about the Python-list mailing list