list.remove()
Deletes the first item in a list that equals the value you give. Raises ValueError when no item matches.
list.remove(x)remove(x) looks through the list from the start and deletes the first item equal to x. The items after it move one place to the left.
Use it when you know the value you want gone, such as a name or a product. If you know the position instead, use list.pop() or del items[i].
Two details trip people up: only the first match is removed, even when the value appears several times, and a value that is not in the list raises a ValueError instead of being quietly ignored.
Parameters
| Parameter | What it is |
|---|---|
xrequired | The value to delete. Items are compared with ==, so 1 and 1.0 count as equal. |
Return value
Nothing (None). The list is changed in place.
Examples
1Remove a name from a list
guests = ["Ana", "Ben", "Chloe"]
guests.remove("Ben")
print(guests)['Ana', 'Chloe']
2Only the first match goes
cart = ["apple", "pear", "apple", "kiwi"]
cart.remove("apple")
print(cart)['pear', 'apple', 'kiwi']
3Check first to avoid the error
tags = ["news", "sport"]
for tag in ["sport", "music"]:
if tag in tags:
tags.remove(tag)
print("removed", tag)
else:
print(tag, "was not there")
print(tags)removed sport music was not there ['news']
4Remove every copy of a value
remove() deletes one item at a time. To drop all of them, build a new list with a list comprehension.
readings = [5, 0, 7, 0, 0, 3]
readings = [r for r in readings if r != 0]
print(readings)[5, 7, 3]
Common mistakes
Removing a value that is not in the list
This raises ValueError. Test with in first, or catch the error.
colors = ["red", "blue"]
try:
colors.remove("green")
except ValueError:
print("ValueError: green is not in the list")
print(colors)ValueError: green is not in the list ['red', 'blue']
Removing items while looping over the same list
Each removal shifts the remaining items left, so the loop skips the next one. Loop over a copy (for x in items[:]) or build a new list.
nums = [2, 2, 3, 4]
for n in nums:
if n == 2:
nums.remove(n)
print(nums)
nums = [2, 2, 3, 4]
for n in nums[:]:
if n == 2:
nums.remove(n)
print(nums)[2, 3, 4] [3, 4]
Questions people ask
What is the difference between remove(), pop() and del?
remove(x) deletes by value. list.pop() deletes by position and gives you the item back. del items[i] deletes by position (or a whole slice) and gives nothing back.
How do I remove all occurrences of a value?
Use a list comprehension: items = [x for x in items if x != value].
How do I remove an item without an error if it is missing?
Check first: if x in items: items.remove(x). If you do not need duplicates or order, a set with set.discard() never raises.