Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Lists, Tuples and Ranges

Python list.remove() method

Reference for Python list.remove(): delete the first item equal to a value, ValueError when it is missing, removing all matches safely, and pop() and del compared.

The remove() method deletes the first item in a list that equals the value you pass. The list is changed in place and the method returns None. If the value is not present, Python raises ValueError.

Only one item is removed per call. If the value occurs several times, the later copies stay, which surprises many beginners.

Python
fruits = ["apple", "pear", "apple"]
fruits.remove("apple")
print(fruits)   # ['pear', 'apple']

Try it

Python Removing by value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Removing every match

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
list.remove(value)
Name Description
value The object to remove. The first item that compares equal with == is deleted.

Return value: None.

Raises: ValueError if no item equals value.

Usage notes

  • First match only. To drop every occurrence, build a new list with a comprehension ([x for x in items if x != value]) or assign back with a slice (items[:] = ...) when other references must see the change.
  • Missing values raise. Check with value in items or catch ValueError. The check and the removal each scan the list, which is fine for small lists.
  • Do not remove while iterating the same list. The loop skips elements as they shift left, as the wrong example shows (one of the two adjacent 2 values survives).
  • Equality, not identity. 1, 1.0 and True match each other. For lists of objects, equality uses __eq__.
  • Linear time. The search is O(n) and the shift of later items is O(n).
  • Choose the right tool. Know the value: remove(). Know the position: del items[i]. Need the removed value back: pop(). Want everything gone: clear().
  • Returns None. Writing items = items.remove(x) loses your list.
  • Sets have remove() too, which raises KeyError, and discard() which never raises.