The remove() method removes the first matching element (which is passed as an argument) from the list.
The syntax of the remove()
method is:
list.remove(element)
remove()
method takes a single element as an argument and removes it from the list.element
doesn’t exist, it throws ValueError: list.remove(x): x not in list exception.The remove()
doesn’t return any value (returns None
).
# animals list
animals = ['cat', 'dog', 'rabbit', 'guinea pig']
# 'rabbit' is removed
animals.remove('rabbit')
# Updated animals List
print('Updated animals list: ', animals)
Output
Updated animals list: ['cat', 'dog', 'guinea pig']
If a list contains duplicate elements, the remove()
method only removes the first matching element.
# animals list
animals = ['cat', 'dog', 'dog', 'guinea pig', 'dog']
# 'dog' is removed
animals.remove('dog')
# Updated animals list
print('Updated animals list: ', animals)
Output
Updated animals list: ['cat', 'dog', 'guinea pig', 'dog']
Here, only the first occurrence of element ‘dog’ is removed from the list.
# animals list
animals = ['cat', 'dog', 'rabbit', 'guinea pig']
# Deleting 'fish' element
animals.remove('fish')
# Updated animals List
print('Updated animals list: ', animals)
Output
Traceback (most recent call last):
File ".. .. ..", line 5, in <module>
animal.remove('fish')
ValueError: list.remove(x): x not in list
Here, we are getting an error because the animals
list doesn’t contain 'fish'
.
#python