Python List remove() Method
Last Updated :
09 Dec, 2024
Python list remove() function removes the first occurrence of a given item from list. It make changes to the current list. It only takes one argument, element you want to remove and if that element is not present in the list, it gives ValueError.
Example:
Python
a = ['a', 'b', 'c']
a.remove("b")
print(a)
List remove() Syntax
list_name.remove(obj)
Parameter
- obj: object to be removed from the list
Returns: The method does not return any value but removes the given object from the list.
Exception: If the element doesn’t exist, it throws ValueError: list.remove(x): x not in list exception.
Passing list as argument in remove()
Using the remove() method with a list as an argument in Python isn’t directly supported. The remove() method is designed to remove a single element from the list, not another list.
Python
a = [1, 2, 2, 3, 4, 4, 5, 6, 6, 7]
a.remove([1,2])
print(a)
Output
Traceback (most recent call last):
File "Solution.py", line 4, in <module>
a.remove([1,2])
ValueError: list.remove(x): x not in list
If we want to remove multiple elements from a list (like removing all elements that are present in another list), we can do this by iterating through the second list and using the remove() method for each of its elements.
Python
# Original list
a = [1, 2, 3, 4, 5, 6, 7, 8]
# List of elements to remove
b = [2, 4, 6]
# Remove elements from main_list that are in remove_list
for item in b:
if item in a:
a.remove(item)
# Print the updated main_list
print(a)
Trying to delete Element that doesn’t Exist
In this example, we are removing the element ‘e’ which does not exist in the list which will result in a ValueError. We can use a try except block to handle these exceptions.
Python
a = [ 'a', 'b', 'c', 'd' ]
a.remove('e')
print(a)
Output
Traceback (most recent call last):
File "Solution.py", line 4, in <module>
a.remove('e')
ValueError: list.remove(x): x not in list
Similar Reads: