Re: Removing elements from a list while iterating...

Aaron Watters (aaron@funcity.njit.edu)
Tue, 21 Mar 1995 18:18:30 GMT

In article <3jv91u$lc2@euas20.eua.ericsson.se> euamli@eua.ericsson.se (Magnus Lindberg) writes:
>skip@dolphin.automatrix.com (Skip Montanaro) writes:
>
>>We all know this is unsafe:
>
>> for m in list:
>> if m matches some criterion:
>> list.remove(m)
>
>>since the list is mutating out from under the internal pointers that the for
>>loop is using.....

Well, if you're removing just a few items, why not:

bad = {}
for m in list:
if m matches some criterion:
bad[m] = m
for m in bad.values():
list.remove(m)

or if you're removing most of the items, and you want
the items to be unique in the remaining list, and you don't care
about the order of the result, why not:

good = {}
for m in list:
if not good.has_key(m) and not (m matches some criterion):
good[m] = m
list = good.values()

[omit the has_key thing if there aren't any redundancies, or
if the criterion test is cheap.]

In general I consider dictionaries to be absolute magic, and you can
avoid lots of questionable and expensive operations on lists if you
use them (intelligently, of course).

-a.
====
``Yeah, I've mellowed. For instance I was at some restaurant in
New York and this lady comes up to me and talks about how she,
her daughter, and her granddaughter all attended one of my concerts
together, and I wanted to say `Get away from me you old bag!'
But instead, I smiled and was very polite.''
-- Mick Jagger, in an interview, aging gracelessly.
``...time waits for no one, and it won't wait for me-e-e.''