This post will discuss how to remove all occurrences of an item from a list in Python.

1. Using list.remove() function

list.remove(x) removes the first occurrence of value x from the list, but it fails to remove all occurrences of value x from the list.

Download  Run Code

 
To remove all occurrences of an item from a list using list.remove(), you can take advantage of the fact that it raises a ValueError when it can’t find the specified item in the list. The idea is to repeatedly call remove() function until it raises a ValueError exception. This is demonstrated below:

Download  Run Code

2. Using List Comprehension

The recommended solution is to use list comprehension. With list comprehensions, you can create a sublist of those elements that satisfy a certain condition. A list comprehension consists of an expression, followed by a for-loop, followed by an optional for-loop or if-statement enclosed within the square brackets [].

Here’s a working example using list comprehension, which is more concise and readable, and more Pythonic than the above code:

Download  Run Code

3. Using filter() function

You can also use the built-in function filter(function, iterable), which can construct an iterator from the list elements (an iterable) for which function returns true.

Note that filter(function, iterable) is equivalent to the generator expression (item for item in iterable if function(item)). This is demonstrated below:

Download  Run Code

That’s all about removing all occurrences of an item from a list in Python.