iterating over collection, deleting entries

Andrea Griffini agriff at tin.it
Sun Apr 25 13:36:43 EDT 2004


On Sun, 25 Apr 2004 18:25:08 +0200, "Patrick von Harsdorf"
<patrick at harsdorf.de> wrote:

>Please tell me, what´s the best way to do this?

I'm pretty new to python, but normally this is done
by a simple read-write approach. You iterate over
the elements using a "read" pointer, and every time
you find one you want to keep you just write it
and increment the write pointer.
In code...

   wrp = 0

   for x in container:
     if is_good(x):
       container[wrp] = x
       wrp += 1

   del container[wrp:]

This is O(n) and doesn't require any additional memory

I suppose however that it's not so common finding
cases in which this is much better than...

   a = [x for x in a if is_good(x)]

The latter will allocate a list for the result
(instead of reusing the same), but can free the
original (and this may be *better* than just
resizing it - it may be better in C++, for example).

HTH
Andrea



More information about the Python-list mailing list