![]() |
VOOZH | about |
The task is to perform the operation of removing all the occurrences of a given item/element present in a list.
Example
Input1: 1 1 2 3 4 5 1 2 1 Output1: 2 3 4 5 2 Explanation : The input list is [1, 1, 2, 3, 4, 5, 1, 2] and the item to be removed is 1. After removing the item, the output list is [2, 3, 4, 5, 2]
Below are the ways by which we can remove all the occurrences of an Element from a List in Python:
The list comprehension can be used to perform this task in which we just check for a match and reconstruct the list without the target element. We can create a sublist of those elements in the list that satisfies a certain condition.
The original list is : [1, 3, 4, 6, 5, 1] The list after performing the remove operation is : [3, 4, 6, 5]
Time complexity: O(n)
Auxiliary Space: O(n)
We filter those items of the list which are not equal __ne__ to the item. In this example, we are using filter() and __ne__ to remove all the occurrences of an element from the list.
The original list is : [1, 3, 4, 6, 5, 1] The list after performing the remove operation is : [3, 4, 6, 5]
Time Complexity: O(n)
Auxiliary Space: O(n)
In this method, we iterate through each item in the list, and when we find a match for the item to be removed, we will call remove() function on the list.
The original list is :[1, 3, 4, 6, 5, 1] The list after performing the remove operation is :[3, 4, 6, 5]
Time Complexity: O(n^2), where n is the length of the input list.
Auxiliary Space: O(1)
In this example, we are converting the list into the string and then replacing that element string with empty space such that all occurrences of that element is removed.
[3, 4, 6, 5]
Time Complexity: O(n)
Auxiliary Space: O(n)
In this example, we are making a new list that doesn't contain any of that particular element's occurrences inside the list by using enumerate function.
[3, 4, 6, 5]
Time Complexity: O(n)
Auxiliary Space: O(n)