remove() method is used to remove the first occurrence of a specified element from a list. It modifies the original list directly and does not create a new list. If the specified element is not found, a ValueError is raised.
Example: In this example, remove() is used to remove an element from a list.
a = ["apple", "banana", "orange"]
a.remove("banana")
print(a)
Output
['apple', 'orange']
Explanation: a.remove("banana") removes the first occurrence of "banana" from the list. The original list is updated directly.
Syntax
list.remove(element)
- Parameter: element - item to remove from the list.
- Return Value: Does not return any value. Removes the specified element from the list.
Examples
Example 1: In this example, a value is removed from a list using remove(). The method searches for the specified element and removes its first occurrence.
a = [10, 20, 30, 40]
a.remove(30)
print(a)
Output
[10, 20, 40]
Explanation: a.remove(30) removes 30 from the list.
Example 2: Here, the same value appears multiple times in the list. The remove() method removes only the first matching occurrence.
a = [5, 10, 5, 15, 5]
a.remove(5)
print(a)
Output
[10, 5, 15, 5]
Explanation: a.remove(5) removes only the first occurrence of 5. The remaining occurrences stay unchanged.
Example 3: In this example, we check whether an element exists before removing it. This prevents a ValueError from occurring.
a = ["red", "blue", "green"]
if "blue" in a:
a.remove("blue")
print(a)
Output
['red', 'green']
Explanation:
- "blue" in a checks whether the element exists in the list.
- a.remove("blue") executes only when the element is present.