This tutorial will discuss how to remove all occurrences of an element in a Python list.
To remove all occurrences of an element from a list, we can iterate over all the elements of the list and skip the elements we don’t want to include.
This can be accomplished using list comprehension. We’ve created a separate function that takes the list as its first argument and the target element we want to delete as the second argument.
def removeAllInstances(listObj, targetElement): # Using list comprehension to filter out the targetElement return [item for item in listObj if item != targetElement]
The function uses list comprehension to generate a new list, excluding the specified element.
In this way, we can remove all occurrences of a given element from the list. If we call this function with a list and the value 22 as arguments, it will remove all occurrences of the value 22 from the list.
Let’s see the complete example,
def removeAllInstances(listObj, targetElement): # Using list comprehension to filter out the targetElement return [item for item in listObj if item != targetElement] # Test the function sampleList = [45, 67, 22, 45, 22, 89, 71, 22, 51] print("Original List:", sampleList) # Remove all occurrences of value sampleList = removeAllInstances(sampleList, 22) print("List after removing all instances of 22 : ", sampleList)
Output
Frequently Asked:
Original List: [45, 67, 22, 45, 22, 89, 71, 22, 51] List after removing all instances of 22 : [45, 67, 45, 89, 71, 51]
Summary
Today, we learned how to remove all occurrences of an element in a Python list.