How to Remove All Occurrences of a Value In a List in Python



Python


In this article, we show how to remove all occurrences of a value in a list in Python.

If you use the remove() function on a list in Python, this will remove only the first occurrence of the value that you want to delete. The remove() function, by itself, does not remove all occurrences of a value from a list.

In order to remove all occurrences of a value from a list, we need to combine a for loop, an if statement, and then have a second empty list that will append every item that isn't 'grape' onto the list. We later can then set the original list to this list we have created.

Let's imagine we have a list with a value that appears many times and we want to remove all occurrences of this value.

In our code below, 'grape' is present



So we have a list, list1, which has 8 elements.

We then create a second empty list, list2. This list will function to append all elements that aren't equal to 'grape'. If you want to exclude another value, you just add the keyword, and, along with all the other values you want to exclude.

We set i to 0, because the first element in a list is at an index location of 0.

We then have a for loop that starts at index location 0 and goes the entire length to the end of the list.

We then have an if statement that if the element isn't equal to 'grape', it gets appended to the variable, list2.

We then show the contents of list2 and see that all occurrences of the value 'grape' have been excluded from the list.

We then copy the contents of list2 to list1, so that we now have the original list in the original variable with all occurrences of the value removed.

We then show the contents of list1, which is now the originl list with all values of the string 'grape' removed.

And this is how we can remove all occurrences of a value in a list in Python.


Related Resources

How to Get the Number of Items in a List in Python

How to Get the Last Item in a List in Python



HTML Comment Box is loading comments...