How to Remove All Occurrences of an Element from a List in Python?

Estimated read time 1 min read

You can remove all occurrences of an element from a list in Python by using a list comprehension that filters out the elements that match the specified element. Here’s an example:

my_list = [1, 2, 3, 2, 4, 2, 5]
element_to_remove = 2
new_list = [x for x in my_list if x != element_to_remove]
print(new_list) # Output: [1, 3, 4, 5]

In this example, we have a list (my_list) that contains multiple occurrences of a specified element (2). We want to remove all occurrences of the element from the list. We achieve this by using a list comprehension that filters out the elements that match the specified element. The resulting list (new_list) contains all the elements of the original list except for the specified element.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply