Delete all occurrences of an element from a list in python

In this article we shall see how to remove all occurrences of an element from a list in python assuming that our list has duplicate elements. This can be done in a number of ways. Let us look at all the possible approaches one by one.

  1. The naive approach
  2. filter method with not equal operator
  3. filter method with lambda function
  4. list comprehension
  5. slicing (slice assignment)

Based on the time complexity and code complexity choose the best one for you.

The naive approach

In the naive approach we will use a while loop to check if the element to be removed is present in the list. If it is present we will use the remove() method to delete the element from the list. Let us look at it with an example.

numbers = [1, 2, 3, 2, 2, 2, 5]

val = 2
while val in numbers:
    numbers.remove(val)

print(numbers)

The output of the above code is,

[1, 3, 5]

The number of times the loop executed will be equal to the number of elements that we want to delete.

filter method with not equal operator

A filter method can take an iterator and a condition/function and returns an object with only the elements that satisfies the condition.

A not equal operator will return True if the operands are different or not equal. In my case I would like to remove all the 2 from the numbers list.

numbers = [1, 2, 3, 2, 2, 2, 5]

print(list(filter((2).__ne__, numbers)))

The output of this code is,

[1, 3, 5]

filter method with lambda function

Just like the above approach we will be using a filter class here also but instead of checking the inequality we will use lambda function.

The lambda function can be written like this.

lambda x: x != element_to_be_deleted

Which is nothing but the lambda function takes an iterator and check if the element is not equal to the element to be deleted.

numbers = [1, 2, 3, 2, 2, 2, 5]

print(list(filter(lambda x: x != 2, numbers)))

The output of the above code is,

[1, 3, 5]

list comprehension

The next approach is to use a list comprehension. We will be creating a new list excluding the elements that we wish to delete.

numbers = [1, 2, 3, 2, 2, 2, 5]

val = 2
numbers = [num for num in numbers if num != val]
print(numbers)

The output of this code is,

[1, 3, 5]

slicing (slice assignment)

This approach will modify the original list and combine the functionality of a list comprehension.

numbers = [1, 2, 3, 2, 2, 2, 5]

val = 2
numbers[:] = (num for num in numbers if num != val)
print(numbers)

The output of the above code is,

[1, 3, 5]

Conclusion

Hope this article is helpful. Choose the approach that better suit your needs. If you have any doubts mention them in the comments.

Happy coding !