How to remove items from a list while iterating?

lfaraone picture lfaraone · Jul 30, 2009 · Viewed 570.2k times · Source

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.

Answer

David Raznick picture David Raznick · Jul 30, 2009

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 the sake of clarity and for those who find the use of the [:] notation hackish or fuzzy, here's a more explicit alternative. Theoretically, it should perform the same with regards to space and time than the one-liners above.

temp = []
while somelist:
    x = somelist.pop()
    if not determine(x):
        temp.append(x)
while temp:
    somelist.append(templist.pop())

It also works in other languages that may not have the replace items ability of Python lists, with minimal modifications. For instance, not all languages cast empty lists to a False as Python does. You can substitute while somelist: for something more explicit like while len(somelist) > 0:.