Sub topic 6
Removing Items with remove, pop, del and clear
This chapter assumes you can create a list, read items by index, and know that lists are mutable (you can change them after creating them). You should also be comfortable with for loops and calling methods. By the end you will know which of four removal tools fits a given job, what each one returns, and which errors each can raise.
Four tools, four questions
Python has no single "delete" operation for lists. Each tool answers a different question about what you know.
| Tool | You know... | Returns | Fails with |
|---|---|---|---|
| `list.remove(x)` | the value | `None` | `ValueError` if `x` is absent |
| `list.pop(i)` | the position (default: last) | the removed item | `IndexError` if the list is empty or `i` is out of range |
| `del list[i]` or `del list[a:b]` | a position or a range | nothing (it is a statement) | `IndexError` for a bad single index |
| `list.clear()` | nothing, you want all items gone | `None` | never |
All four change the list in place. None of them creates a new list.
remove: delete by value
remove(x) scans from the left and deletes the first item that equals x. It stops after one deletion, so later duplicates stay.
colors = ["red", "green", "blue", "green"]
colors.remove("green")
print(colors) # ['red', 'blue', 'green']
try:
colors.remove("purple")
except ValueError:
print("purple was not in the list")Two details matter in practice.
- Matching uses
==, not identity. Because1 == True == 1.0in Python,removecan delete an item you did not expect. - A missing value raises
ValueError. Python has no "remove if present" variant, so you either catch the error or test first within.
flags = [1, True, 1.0]
flags.remove(True)
print(flags) # [True, 1.0] (the int 1 matched first)
names = ["ana", "bo"]
if "cy" in names:
names.remove("cy")
print(names) # ['ana', 'bo']The in check followed by remove scans the list twice. For short lists that is fine. For a hot loop over long lists, a try/except ValueError does one scan in the common case.
pop: delete by position and get the item back
pop() removes and returns the last item. pop(i) does the same for index i, and negative indices work.
stack = [10, 20, 30, 40]
print(stack.pop()) # 40
print(stack.pop(0)) # 10
print(stack) # [20, 30]
print(stack.pop(-1)) # 30
print(stack) # [20]pop is the only one of these methods that returns something useful. If you write x = items.remove(3), x is None. If you need the item and its removal in one step, use pop.
Popping from an empty list, or with an index past the end, raises IndexError:
empty = []
try:
empty.pop()
except IndexError as err:
print("cannot pop:", err) # cannot pop: pop from empty listdel: a statement for indexes and slices
del is a statement, not a method, so it has no return value and no parentheses. It accepts a single index or a slice, which makes it the only tool here that can remove several items at once.
data = list(range(10)) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
del data[0] # [1, 2, 3, 4, 5, 6, 7, 8, 9]
del data[-1] # [1, 2, 3, 4, 5, 6, 7, 8]
del data[2:4] # [1, 2, 5, 6, 7, 8]
del data[::2] # [2, 6, 8] (indexes 0, 2, 4 removed)
print(data) # [2, 6, 8]
del data[:] # same effect as data.clear()
print(data) # []A few rules:
- A single out-of-range index raises
IndexError. - A slice never raises for out-of-range bounds.
del data[5:100]on a short list quietly removes whatever exists, and removes nothing if nothing matches. - An extended slice such as
[::2]removes every second item. Python requires exactly the right number of items only for assignment to an extended slice, not fordel. del data(without brackets) is different. It deletes the namedata, not the list contents. Other names bound to the same list still see the items.
clear: empty the list but keep the object
clear() removes every item and leaves the same list object in place. It is equivalent to del items[:].
The difference between clear() and items = [] matters whenever another name refers to the same list.
a = [1, 2, 3]
b = a
a = [] # rebinds a to a new list
print(b) # [1, 2, 3] (b still sees the old list)
a = [1, 2, 3]
b = a
a.clear() # empties the shared list
print(b) # []This applies to function parameters too. Assigning buf = [] inside a function only changes the local name. If the caller expects its list to be emptied, call buf.clear().
Removing items while looping
Removing from a list while a for loop walks over it skips items. The loop tracks a position, and each removal shifts the remaining items one place left, so the item that slid into the current position is never visited.
nums = [2, 4, 6, 7]
for n in nums:
if n % 2 == 0:
nums.remove(n)
print(nums) # [4, 7] (4 was skipped, so it stayed)Three safe patterns:
# 1. Build a new list with a comprehension (usually the best choice).
nums = [2, 4, 6, 7]
odds = [n for n in nums if n % 2 != 0]
print(odds) # [7]
# 2. Change the original list in place through a slice assignment.
nums[:] = [n for n in nums if n % 2 != 0]
print(nums) # [7]
# 3. Loop over a copy while changing the original.
nums = [2, 4, 6, 7]
for n in nums.copy():
if n % 2 == 0:
nums.remove(n)
print(nums) # [7]Pattern 2 matters when other names must see the change, because it keeps the same list object. When you loop by index, go backwards so deletions do not shift the indexes you have not reached yet:
nums = [2, 4, 6, 7]
for i in range(len(nums) - 1, -1, -1):
if nums[i] % 2 == 0:
del nums[i]
print(nums) # [7]To remove every occurrence of one value, avoid while x in items: items.remove(x). It rescans from the left each time, so its cost grows with the square of the list length. Use items = [i for i in items if i != x] instead.
What each removal costs
A list stores its items in one contiguous block. Removing an item from the middle means every later item shifts left to close the gap.
| Operation | Typical cost | Why |
|---|---|---|
| `pop()` | constant (O(1)) | nothing shifts |
| `pop(0)`, `del items[0]` | O(n) | every item shifts |
| `remove(x)` | O(n) | a scan, then a shift |
| `del items[a:b]` | O(n) | one shift for the whole slice |
| `clear()` | O(n) | each reference is released |
Deleting a slice is cheaper than deleting the same items one at a time, because the shift happens once. If you repeatedly remove from the front, a list is the wrong container. A later chapter covers collections.deque, which removes from the front in constant time.
Choosing quickly
- You have the value and want it gone:
remove. - You have a position and want the item back:
pop. - You have a position or range and do not need the item:
del. - You want an empty list that other references still share:
clear. - You want to keep only items that pass a test: a comprehension, not repeated removal.
Exercise
After running the code below, what are items and got? Explain why items.remove(2) is not a good way to remove the item at index 2.
items = [5, 2, 9, 2]
got = items.pop(2)
items.remove(2)
Show answer
got is 9, because pop(2) removes and returns the item at index 2, leaving [5, 2, 2]. Then remove(2) deletes the first item equal to 2, leaving items == [5, 2]. remove works on values, not positions, so items.remove(2) would not target index 2. It targets the first value 2 wherever it is.
Exercise
Fix this function so the caller's list is emptied, and say why the original does nothing. def reset(buf): buf = [] data = [1, 2, 3] reset(data) print(data)
Show answer
Replace the body with buf.clear(). In the original, buf = [] rebinds the local name buf to a new empty list and leaves the caller's list untouched, so print(data) shows [1, 2, 3]. buf.clear() mutates the shared list object, so data prints [].