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

iterating over collection, deleting entries

P: n/a
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[i]
if isBad(item) del collection[i]

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?
--
Patrick von Harsdorf
pa*****@harsdorf.de


Jul 18 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
Sorry, I missed that SnuSnu just posed a very similar question.
Please ignore my post...
Jul 18 '05 #2

P: n/a
On Sun, 25 Apr 2004 18:25:08 +0200, "Patrick von Harsdorf"
<pa*****@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
Jul 18 '05 #3

P: n/a
I would do:

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

Larry Bates
Syscon, Inc.
"Patrick von Harsdorf" <pa*****@harsdorf.de> wrote in message
news:c6*************@news.t-online.com...
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[i]
if isBad(item) del collection[i]

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?
--
Patrick von Harsdorf
pa*****@harsdorf.de

Jul 18 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.