The best answers to the question “How to remove items from a list while iterating?” in the category Dev.
I’m iterating over a list of tuples in Python, and am attempting to remove them if they meet certain criteria.
for tup in somelist: if determine(tup): code_to_remove_tup
What should I use in place of
code_to_remove_tup? I can’t figure out how to remove the item in this fashion.
The answers suggesting list comprehensions are ALMOST correct — except that they build a completely new list and then give it the same name the old list as, they do NOT modify the old list in place. That’s different from what you’d be doing by selective removal, as in @Lennart’s suggestion — it’s faster, but if your list is accessed via multiple references the fact that you’re just reseating one of the references and NOT altering the list object itself can lead to subtle, disastrous bugs.
Fortunately, it’s extremely easy to get both the speed of list comprehensions AND the required semantics of in-place alteration — just code:
somelist[:] = [tup for tup in somelist if determine(tup)]
Note the subtle difference with other answers: this one is NOT assigning to a barename – it’s assigning to a list slice that just happens to be the entire list, thereby replacing the list contents within the same Python list object, rather than just reseating one reference (from previous list object to new list object) like the other answers.
You can use a list comprehension to create a new list containing only the elements you don’t want to remove:
somelist = [x for x in somelist if not determine(x)]
Or, by assigning to the slice
somelist[:], you can mutate the existing list to contain only the items you want:
somelist[:] = [x for x in somelist if not determine(x)]
This approach could be useful if there are other references to
somelist that need to reflect the changes.
Instead of a comprehension, you could also use
itertools. In Python 2:
from itertools import ifilterfalse somelist[:] = ifilterfalse(determine, somelist)
Or in Python 3:
from itertools import filterfalse somelist[:] = filterfalse(determine, somelist)
for i in range(len(somelist) - 1, -1, -1): if some_condition(somelist, i): del somelist[i]
You need to go backwards otherwise it’s a bit like sawing off the tree-branch that you are sitting on 🙂
Python 2 users: replace
xrange to avoid creating a hardcoded list
You need to take a copy of the list and iterate over it first, or the iteration will fail with what may be unexpected results.
For example (depends on what type of list):
for tup in somelist[:]: etc....
>>> somelist = range(10) >>> for x in somelist: ... somelist.remove(x) >>> somelist [1, 3, 5, 7, 9] >>> somelist = range(10) >>> for x in somelist[:]: ... somelist.remove(x) >>> somelist