In this article, we will see different ways to remove all occurrences or instances of a given element from the list in Python.
Let’s see the example:
Example:
Now, let’s see different methods:
Table of Contents [hide]
Using remove() method of list with for loop
remove()
method is used to remove the 1st occurrence of given element from the list. So here we are looping through the list, and whenever we find the given element, then we will remove that element from the list using remove() method.
Here is Python code:
Output:
Using pop() method of list
pop()
method is used to remove the 1st occurrence of given index element from the list. So here we are looping through the list, and whenever we find the given element, then we will remove that element from the list using pop() method by passing its corresponding index.
Here is Python code:
Output:
Using list-comprehension
Here, we are creating a new list by adding elements that are not matching with the given element using list-comprehension
.
This is recommended solution to use, and here we are creating a sublist that satisfies certain conditions. In this scenario, if item
is not matching with the given element
Here is Python code:
Output:
Using filter()
We can also use inbuilt filter(function,iterable)
method which can return an itertor from elements of the list for which function returns true.
Here is Python code:
Using remove() method of list with while loop
We can also use remove()
method with while loop rather than for loop as seen in first approach.
We will iterate the elements using while loop and when we find the element in the list, we will remove it.
Here is Python code:
Output:
That’s all about how to remove all occurrences or instances of a given element from the list in Python.