A list is a container data type that represents a collection of ordered elements in which each elements has an index relative to other elements in the list. Lists are mutable meaning that operations such as insertions and removal can be done to a list in-place without creating a new list.
The remove()
method removes the leftmost occurrence of an item from a list.
lst.remove(item)
item |
The item to be removed. |
The remove method removes the first occurrence of the input value from the list and returns None
. If the element is not in the list, a ValueError
is raised.
As mentioned above, a ValueError
is raised if the element does not exist in the list.
remove() method on a list with duplicate elements
If the list contains duplicate elements, only the first matching element is removed.
Remove all occurrences of an item from the list
We can call the remove()
method repeatedly using a loop, to remove all the occurrences of an item from the list.
In the above example, the for
loop iterates through the list elements. The if
condition in the loop body checks whether the current element is equal to the element to be removed, if so, the remove()
method is called. The net outcome is that all the occurrences of the item are removed from the list by the time the loop terminates.
We can also use a while
loop together with the the count()
method to achieve the same. The count()
method returns the number of times that an element appears in a list, we will use it to check whether the item exists before calling the remove()
method.
In the above example, we used a while
loop with a condition to check whether the element appears in the list or not. If the element's count is greater than 0, the loop body is executed and the leftmost element is removed, else, the condition fails and the loop terminates.
Alternatively, we can also catch the ValueError
when it is raised using the try-catch
statement instead of using the count()
method.