When I am writing code in Python, I often need to remove items from a list or other sequence type based on some criteria. I haven't found a solution that is elegant and efficient, as removing items from a list you are currently iterating through is bad. For example, you can't do this:
for name in names:
if name[-5:] == 'Smith':
names.remove(name)
I usually end up doing something like this:
toremove = []
for name in names:
if name[-5:] == 'Smith':
toremove.append(name)
for name in toremove:
names.remove(name)
del toremove
This is innefficient, fairly ugly and possibly buggy (how does it handle multiple 'John Smith' entries?). Does anyone have a more elegant solution, or at least a more efficient one?
How about one that works with dictionaries?
You can also iterate backwards over the list:
This has the advantage that it does not create a new list (like
filter
or a list comprehension) and uses an iterator instead of a list copy (like[:]
).Note that although removing elements while iterating backwards is safe, inserting them is somewhat trickier.