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
Release: 2024-12-25 06:10:16
Original
990 people have browsed it

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'?
Copy after login

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)]
Copy after login

Alternatively, assigning to the slice somelist[:] mutates the existing list:

somelist[:] = [x for x in somelist if not determine(x)]
Copy after login

For direct mutation, the itertools module provides the filterfalse function:

  • Python 2:
from itertools import ifilterfalse
somelist[:] = ifilterfalse(determine, somelist)
Copy after login
  • Python 3:
from itertools import filterfalse
somelist[:] = filterfalse(determine, somelist)
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template