iterating over collection, deleting entries

Patrick von Harsdorf patrick at harsdorf.de
Sun Apr 25 12:25:08 EDT 2004


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
patrick at harsdorf.de







More information about the Python-list mailing list