Python List type provides the
remove() method as a built-in method to remove items from the current list. The remove() method provides very simple usage where the item or object we want to remove is provided to the remove() method as a parameter.
List remove() Method Syntax
The list remove() method has a very simple syntax which is like below. The remove() method does not return anything or returns nothing.
- LIST is the list where the specified ITEM will be removed.
- ITEM is an object or value which will be removed from the specified LIST.
Remove Element/Item From List
The remove() method can be used to remove an element or item from the list. In the following example, we remove the item “1” from the list named numbers.
numbers = [1,2,3,4,5] numbers.remove(1)
The output is like below where the item “1” does not exist.
Try Removing Non-Existing Element/Item From List
When we try to remove an element or item which do not exist in the specified list the “ValueError” or exception is printed. In the following example, we try to remove the “9” from the list named “numbers” which does not contain “9”.
numbers = [1,2,3,4,5] numbers.remove(9)
Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: list.remove(x): x not in list
Try To Remove Duplicate Elements/Items
A list may contain duplicate elements or items. When the remove() method is called for a duplicate item only a single item is removed. The first occurrence of the specified item is removed and other instances are not removed.
numbers = [1,2,2,3,4,4,4,5] numbers.remove(4) print(numbers)
[1, 2, 2, 3, 4, 4, 5]
Remove Duplicate Elements/Items
We can use the
count() method of the list in order to count duplicate items we want to remove and iterate until there is no item in the list. In the following example, we remove the duplicate item “4” from the list “numbers”.
numbers = [1,2,2,3,4,4,4,5] while numbers.count(4): numbers.remove(4) print(numbers)
[1, 2, 2, 3, 5]
Alternatively following a single line while syntax can be used to remove all of the specified duplicate items or elements.
numbers = [1,2,2,3,4,4,4,5] while 4 in numbers: numbers.remove(4) print(numbers)
Remove String Elements/Items
String elements or items can be removed from a list with the remove() method like below.
names = ["ismail","ahmet","ali"] names.remove("ismail")