Home >Backend Development >Python Tutorial >How to Safely Remove Items from a List While Iterating in Python?

How to Safely Remove Items from a List While Iterating in Python?

Susan Sarandon
Susan SarandonOriginal
2024-12-25 06:10:16991browse

How to Safely Remove Items from a List While Iterating in Python?

Iterative Removal of Items from a List

Problem

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'?

Solution

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:

  • Python 2:
from itertools import ifilterfalse
somelist[:] = ifilterfalse(determine, somelist)
  • Python 3:
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn