Efficient way to remove objects from a list

一首诗 newptcai at gmail.com
Mon Nov 3 09:21:48 EST 2008


Thanks!  That's a more clear way!

On Nov 3, 9:38 pm, Peter Otten <__pete... at web.de> wrote:
> Chris Rebert wrote:
> > On Mon, Nov 3, 2008 at 1:40 AM, 一首诗 <newpt... 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