snippetpythonCritical
How to remove items from a list while iterating?
Viewed 0 times
whilehowlistremoveiteratingitemsfrom
Problem
I'm iterating over a list of tuples in Python, and am attempting to remove them if they meet certain criteria.
What should I use in place of
for tup in somelist:
if determine(tup):
code_to_remove_tupWhat should I use in place of
code_to_remove_tup? I can't figure out how to remove the item in this fashion.Solution
You can use a list comprehension to create a new list containing only the elements you don't want to remove:
Or, by assigning to the slice
This approach could be useful if there are other references to
Instead of a comprehension, you could also use
Or in Python 3:
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)Code Snippets
somelist = [x for x in somelist if not determine(x)]somelist[:] = [x for x in somelist if not determine(x)]from itertools import ifilterfalse
somelist[:] = ifilterfalse(determine, somelist)from itertools import filterfalse
somelist[:] = filterfalse(determine, somelist)Context
Stack Overflow Q#1207406, score: 1134
Revisions (0)
No revisions yet.