list.remove()
Python · Lists
Theory
.remove(value) searches the list from the start and deletes the first item that is equal (==) to value, shifting later items left to close the gap. sales = [100, 250, 300, 250] then sales.remove(250) gives [100, 300, 250]: only the first 250 disappears. If no item matches, it raises ValueError: list.remove(x): x not in list. It returns None.
remove() works by value; to delete by position use pop(index) or del sales[index]. Because it must search and then shift, it is O(n). To remove every occurrence, do not call remove() inside a for loop over the same list, since changing a list while iterating over it skips items. Build a filtered copy instead: sales = [s for s in sales if s != 250]. Guard against the error with if value in sales: before removing.
Why we use it
Lists often contain a value you need to drop: a cancelled order, a placeholder, a bad reading. remove() deletes it by what it is, without you having to find its position first.
When to use it
Use remove() to delete one known value. Use pop() or del when you know the index, a list comprehension to remove all matches, and a set if you frequently delete items by value from a large collection.
How it works
- Call sales.remove(250)
- Scan items from index 0
- Is this item == 250? Yes: Delete it, shift later items left, and stop. No: Move to the next item.
- Reached the end with no match? Yes: Raise ValueError. No: (already removed).
- print(sales) shows [100, 300, 250]
Syntax
list.remove(value)Example
sales = [100, 250, 300, 250]
sales.remove(250)
print(sales)Key points
- Removes only the first occurrence, not all matches
- Raises a ValueError if the value isn't found
- Deletes by value; use pop(i) or del list[i] to delete by position
- Remove all matches with a comprehension: [x for x in s if x != v]
- Do not remove items from a list while looping over it