Removes an item from a list
Usage
Use remove()
method to remove a single item from a list.
The method searches for the first instance of the given item and removes it. If specified item is not found, it raises ‘ValueError’ exception.
Syntax
list.remove(item)
Parameter | Condition | Description |
item | Required | Any item you want to remove |
Remove Single Item
# Remove 'green'
L = ['red', 'green', 'blue']
L.remove('green')
print(L)
# Prints ['red', 'blue']
# Remove item from the nested list
L = ['red', 'green', [1, 2, 3]]
L.remove([1, 2, 3])
print(L)
# Prints ['red', 'green']
The remove()
method removes item based on specified value and not by index. If you want to delete list items based on the index, use pop() method or del keyword.
Remove Duplicate Items
remove()
method searches for the first instance of the given item and removes it.
L = ['red', 'green', 'blue', 'red', 'red']
L.remove('red')
print(L)
# Prints ['green', 'blue', 'red', 'red']
If you want to remove multiple instances of an item in a list, use list comprehension or lambda expression.
# list comprehension
L = ['red', 'green', 'blue', 'red', 'red']
L = [x for x in L if x is not 'red']
print(L)
# Prints ['green', 'blue']
# lambda expression
L = ['red', 'green', 'blue', 'red', 'red']
L = list(filter(lambda x: x is not 'red', L))
print(L)
# Prints ['green', 'blue']
Removing Item that Doesn’t Exist
remove()
method raises an ValueError exception, if specified item doesn’t exist in a list.
L = ['red', 'green', 'blue']
L.remove('yellow')
# Triggers ValueError: list.remove(x): x not in list
To avoid such exception, you can check if item exists in a list, using in operator inside if statement.
L = ['red', 'green', 'blue']
if 'yellow' in L:
L.remove('yellow')