Python List remove() Function
The List remove()
method searches for the first instance of the given item and removes it.
If specified item is not found, it raises ValueError
exception.
Syntax
my_list.remove(item)
remove() Parameters
Python List remove()
method parameters::
Parameter | Condition | Description |
---|---|---|
item | Required | Any item you want to remove |
remove() Return Value
Python List remove()
function does not return a value: it modifies the original list.
Examples
Example 1: Remove a Single Item in a List
The remove()
method removes item based on specified value and not by index.
names = ['Tom', 'Anna', 'David', 'Ryan']
names.remove('Ryan')
print(names) # Output: ['Tom', 'Anna', 'David']
output
['Tom', 'Anna', 'David']
If the element does not exist in the list, it throws ValueError
exception.
If you want to delete list items based on the index, use pop()
method or del
keyword.
Example 2: Remove a List Element in a List
The remove()
method can remove complex elements like lists:
names = ['Tom', 'Anna', ['David', 'Ryan']]
names.remove(['David', 'Ryan'])
print(names) # Output: ['Tom', 'Anna']
output
['Tom', 'Anna']
Example 3: Remove Duplicate Items in a List
The remove()
method searches for the first instance of the given item and removes it.
names = ['Tom', 'Anna', 'David', 'Anna']
names.remove('Anna')
print(names) # Output: ['Tom', 'David', 'Anna']
output
['Tom', 'David', 'Anna']
If you want to remove multiple instances of an item in a list, you can use List Comprehension or Lambda Expression.
For example, use List Comprehension:
names = ['Tom', 'Anna', 'David', 'Anna']
to_remove = 'Anna'
names = [x for x in names if x is not to_remove]
print(names) # Output: ['Tom', 'David']
output
['Tom', 'David']
For example, use Lambda Expression:
names = ['Tom', 'Anna', 'David', 'Anna']
to_remove = 'Anna'
names = list(filter(lambda x: x is not to_remove, names))
print(names) # Output: ['Tom', 'David']
output
['Tom', 'David']
Example 4: Remove Item that does Not Exist in a List
If the element passed to the remove()
method is not in the list, it throws ValueError
(pop index out of range exception).
names = ['Tom', 'Anna', 'David', 'Ryan']
removed = names.remove('Thomas')
output
Traceback (most recent call last):
File "main.py", line 2, in <module>
removed = names.remove('Thomas')
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, and the remove it.
names = ['Tom', 'Anna', 'David', 'Ryan']
to_remove = 'Thomas'
if to_remove in names:
removed = names.remove('Thomas')
print(removed)
else:
print('Element is not in the list.')
print(names)
output
Element is not in the list.
['Tom', 'Anna', 'David', 'Ryan']