PythonPython ListsPython list removal
How do you remove elements using `remove()`?
Question 83 of 88 · Updated
On this page
Use items.remove(value) to remove the first element equal to the specified value. The method modifies the original list and returns None. If no matching element exists, it raises ValueError.
Example: Remove an item from a shopping cart#
PYTHONcart = ['milk', 'bread', 'milk', 'eggs'] cart.remove('milk') print(cart) # ['bread', 'milk', 'eggs']
Notice that the second occurrence of milk remains. One call removes only the first match, not every duplicate.
What if the item is missing?#
If absence is expected, check membership before removing the item:
PYTHONif 'juice' in cart: cart.remove('juice')
This leaves the cart unchanged when juice is absent. Without the check, calling cart.remove('juice') raises ValueError.
Common mistakes#
| Mistake | Correct understanding |
|---|---|
remove(1) deletes index 1 | It searches for the value 1 |
| One call deletes all duplicates | Only the first match is removed |
| Assigning the return value to the list | remove() returns None |
To remove every occurrence of milk, use [item for item in cart if item != 'milk']. This creates a new list containing only the remaining items.
Remember#
Use remove() when you know the value to delete, rather than its position. In CPython, the operation takes O(n) time in the worst case because it searches for a match and may shift later elements.
Try it: What remains after removing 10 once from [10, 20, 10]? The answer is [20, 10].
Official references#
References
- 1.Python Tutorial — More on Listsdocs.python.org
- 2.Mutable sequence typesdocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design