By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,587 Members | 1,643 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,587 IT Pros & Developers. It's quick & easy.

Efficient way to remove objects from a list

P: n/a
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?
Nov 3 '08 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Chris Rebert wrote:
On Mon, Nov 3, 2008 at 1:40 AM, 一首诗 <ne******@gmail.comwrote:
>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.
Nov 3 '08 #2

P: n/a
Thanks! That's a more clear way!

On Nov 3, 9:38 pm, Peter Otten <__pete...@web.dewrote:
Chris Rebert wrote:
On Mon, Nov 3, 2008 at 1:40 AM, һʫ <newpt...@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.

Nov 3 '08 #3

This discussion thread is closed

Replies have been disabled for this discussion.