Home > Backend Development > Python Tutorial > How Can I Remove All Occurrences of a Value from a Python List?

How Can I Remove All Occurrences of a Value from a Python List?

Mary-Kate Olsen
Release: 2024-12-24 10:54:14
Original
742 people have browsed it

How Can I Remove All Occurrences of a Value from a Python List?

Eliminate All Instances of a Value from a List

Unlike the remove() method, which only removes the first occurrence of a value in a list, sometimes it's necessary to delete all instances of that value. Here's how to accomplish this removal:

Functional Strategy:

Python 3.x and 2.x offer several functional approaches:

  • Using filter() with a lambda function:

    x = [1, 2, 3, 2, 2, 2, 3, 4]
    result = list(filter((2).__ne__, x))  # Python 3.x
    result = list(filter(lambda a: a != 2, x))  # Python 3.x and 2.x
    Copy after login
  • Using list comprehension:

    x = [1, 2, 3, 2, 2, 2, 3, 4]
    result = [i for i in x if i != 2]
    Copy after login

The above is the detailed content of How Can I Remove All Occurrences of a Value from a Python List?. 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