Python – Remove all occurrences of an item from the list

Python List – Remove all occurrences of a specific item

At times, when you are working with Python Lists, you may need to remove the items with a specific value. In this tutorial, we shall learn how to remove all of the items, that have a given specific value, from a list.

There are many ways to remove all the Items with a specific value from the List. Following are some of them, which we shall discuss in this tutorial.

  1. Iterate through the items of list and use remove() method when the item’s value matches the item of our interest.
  2. Filter the List with lambda function having a condition that the item should be not the item of our interest.
  3. Iterate over items while the item is in the list and use remove() method.

The second method is preferred as it gives better performance. The other two methods are for learning purpose.

Examples

1. Remove all occurrences of specific item in the list using For loop

In the following example, we iterate through each item in the list, using Python For Loop, and when we find a match for the item to be removed, we will call remove() function on the list.

Python Program

mylist = [21, 5, 8, 52, 21, 87]
r_item = 21

# Remove the item for all its occurrences
for item in mylist:
	if(item==r_item):
		mylist.remove(r_item)

print(mylist)
Run Code Copy

Output

[5, 8, 52, 87]

2. Remove all the occurrences of specific item in the list using Filter

We filter those items of the list which are not equal __ne__ to the item.

Python Program

mylist = [21, 5, 8, 52, 21, 87]
r_item = 21

# Remove the item for all its occurrences
mylist = list(filter((r_item).__ne__, mylist))

print(mylist)
Run Code Copy

Output

[5, 8, 52, 87]

3. Remove all occurrences of specific item in the list using While loop

While there is a match with an item in the list, call remove() function on the list.

Python Program

mylist = [21, 5, 8, 52, 21, 87]
r_item = 21

# Remove the item for all its occurrences
while r_item in mylist: mylist.remove(r_item)

print(mylist)
Run Code Copy

Output

[5, 8, 52, 87]

Summary

In this tutorial of Python Examples, we learned how to remove all occurrences of an item or element from the list, with the help of different approaches.

Related Tutorials

Code copied to clipboard successfully 👍