Home >Backend Development >Python Tutorial >How to Safely Remove Items from a List While Iterating in Python?
Iterating through a list of tuples in Python, attempting to remove elements based on certain criteria:
for tup in somelist: if determine(tup): # How to remove 'tup'?
To remove items while iterating, one approach involves creating a new list containing only the desired elements:
somelist = [x for x in somelist if not determine(x)]
Alternatively, assigning to the slice somelist[:] mutates the existing list:
somelist[:] = [x for x in somelist if not determine(x)]
For direct mutation, the itertools module provides the filterfalse function:
from itertools import ifilterfalse somelist[:] = ifilterfalse(determine, somelist)
from itertools import filterfalse somelist[:] = filterfalse(determine, somelist)
The above is the detailed content of How to Safely Remove Items from a List While Iterating in Python?. For more information, please follow other related articles on the PHP Chinese website!