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.
fruits = ["apple", "pear", "apple"] fruits.remove("apple") print(fruits) # ['pear', 'apple']
Try it
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.
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
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 itemsor catchValueError. 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
wrongexample shows (one of the two adjacent2values survives). - Equality, not identity.
1,1.0andTruematch 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. Writingitems = items.remove(x)loses your list. - Sets have
remove()too, which raisesKeyError, anddiscard()which never raises.
Related
list.pop(),list.clear(),list.index(),list.count(),filter(),list- Lessons: Lists, List methods, List comprehensions