iterating over collection, deleting entries

  • Thread starter Patrick von Harsdorf
  • Start date
P

Patrick von Harsdorf

I want to iterate over a collection and delete all unwanted entries.

for item in collection:
del item

of course doesn´t do anything useful. Two things come to mind:
a) iterating backwards over the collection using indexing, something like:

for i in range(len(collection)-1, -1, -1):
item = collection
if isBad(item) del collection

b) duplicating the collection, iterating over one and deleting from the
other.

Both solutions seem both ugly and expensive to me, solution a)
probably isn´t even O(x) anymore.

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

Patrick von Harsdorf

Sorry, I missed that SnuSnu just posed a very similar question.
Please ignore my post...
 
A

Andrea Griffini

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
 
L

Larry Bates

I would do:

collection=[i for i in collection if not isBad(i)]

Larry Bates
Syscon, Inc.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top