Remove all occurrences of an item from a Python list
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.
1 2 3 4 5 6 7 |
if __name__ == '__main__': l = [0, 1, 0, 0, 1, 0, 1, 1] val = 0 l.remove(val) print(l) # prints [1, 0, 0, 1, 0, 1, 1] |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
if __name__ == '__main__': l = [0, 1, 0, 0, 1, 0, 1, 1] val = 0 try: while True: l.remove(val) except ValueError: pass print(l) # prints [1, 1, 1, 1] |
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:
1 2 3 4 5 6 7 8 9 |
if __name__ == '__main__': l = [0, 1, 0, 0, 1, 0, 1, 1] val = 0 # filter the list to exclude 0's l = [i for i in l if i != val] print(l) # prints [1, 1, 1, 1] |
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:
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': l = [0, 1, 0, 0, 1, 0, 1, 1] val = 0 l = list(filter(lambda x: x != val, l)) print(l) # prints [1, 1, 1, 1] |
That’s all about removing all occurrences of an item from a list in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)