The list
is the most flexible container data type in Python. One feature which contributes to these flexibility is their mutable nature which allows operations to be performed on lists in place.
When removing an object from a list, we can either remove the objects from the original list or create an entirely new list with the target object omitted. Each of these approaches has its own advantages and disadvantages.
When the removal happens to the original list, the process is much faster and convenient since the original list is altered directly. On the other hand, creating a new list introduces additional processing overhead but is much safer since the original list is not altered.
To remove all occurrences of an object from a list, the following approaches can be used:
- Using the filter() function
- Using list comprehension
- Calling the
remove()
method repeatedly.
The approaches, as we will see are far more efficient and convenient than using loops.
Using the filter() function
The builtin filter()
function can be used to create a new list that only contains elements for which a certain condition is True
.
filter(function, mylist)
The function given should take a single argument and return a boolean value(True
/False
). The function
gets applied to all the objects of the list, if function(x)
evaluates to True
the value will be included in the new list, otherwise it will be omitted.
We can use the function remove all occurrences of the target object by making the condition to fail if the object being checked is equivalent to the object to be omitted.
In the above example, we specified lambda x: x != valueToBeRemoved
as the condition, this ensures that if an element in the list is equal to the target object, it will not be included in the new list.
Using list comprehension
List comprehension offers a convenient syntax for creating a list from the elements of another list.
new_list = [<expression> for <item> in old_list if <condition>]
List comprehension allows us to specify a condition which will be checked before elements are added to the new list. We can check that the elements is not the object to be removed in the condition.
Using the remove() method
Both of the previous approaches led to creation of a new list while the original list remained unchanged. The remove()
method performs the removal in place and therefore the original list is altered.
The remove(
) method removes the first occurrence of the input element, we will therefore have to call it repeatedly until all the occurrences have been removed from the target list.
lst.remove(x)
Where x
is the object to be removed.
In the above example we used a for loop to iterate through the elements of the list. We used the if statement to check whether the current item is equal to the object to be removed, if so, the remove()
method of the list is called with the element as the argument.