Python List remove()
The remove() method in Python removes the first occurrence of a specified value from a list.
Syntax
list.remove(item)
Parameter
item (required): The value you want to remove from the list. If the specified value is not in the list, it raises a ValueError.
Return Value
It doesn’t return any value i.e. returns None.
Example 1: Remove an item from the list
my_list = [5, 10, 15, 20]
# Removing 5 from the list
my_list.remove(5)
print(my_list) # [10, 15, 20]
If the specified value appears multiple times in a list, only the first occurrence is removed.
my_list = [5, 10, 15, 20, 5]
my_list.remove(5)
print(my_list) # [10, 15, 20, 5]
Handling Error
If you try to delete an item that doesn’t exist in the list, the remove() method raises a ValueError. To handle this scenario, you can use the try and except block to catch the error and take appropriate action.
my_list = [5, 10, 15, 20]
try:
my_list.remove(50)
print(my_list)
except ValueError as e:
print("Error:", e)
# Output: Error: list.remove(x): x not in list
Key points to remember
(1) Removes the first occurrence: If the specified value appears multiple times in the list, only the first occurrence is removed.
(2) Raises ValueError if not found: If the specified value is not found in the list, a ValueError exception is raised.
(3) Modifies the original list: The remove() method modifies the original list and doesn’t return a new list or any value (None is returned).
If you try to remove an item at the specific index, you can use the pop() method.