Home > Backend Development > Python Tutorial > How to Remove All Instances of a Value from a Python List?

How to Remove All Instances of a Value from a Python List?

Susan Sarandon
Release: 2024-12-17 09:52:25
Original
291 people have browsed it

How to Remove All Instances of a Value from a Python List?

Removing All Occurrences of a Value in a List

Unlike Python's remove() method, which only eliminates the first appearance of a value, the task at hand involves removing all occurrences of a specified value from a given list. To achieve this, various approaches can be employed.

Functional Approach

Leveraging Python's functional programming capabilities, one can utilize the filter() function to selectively remove elements based on a given condition. The following examples demonstrate various ways to approach this:

In Python 3.x:

>>> x = [1, 2, 3, 2, 2, 2, 3, 4]
>>> list(filter((2).__ne__, x))
[1, 3, 3, 4]

>>> list(filter(lambda a: a != 2, x))
[1, 3, 3, 4]

>>> [i for i in x if i != 2]
Copy after login

In Python 2.x:

>>> x = [1, 2, 3, 2, 2, 2, 3, 4]
>>> filter(lambda a: a != 2, x)
Copy after login

The above is the detailed content of How to Remove All Instances 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