Sub topic 6
Removing items with remove, pop, del and clear
This chapter assumes you know how to create a list, read items by index, and that lists are mutable. Python gives you four ways to take items out of a list. Each one answers a different question: remove by value, remove by position and keep the item, remove by position or slice, or remove everything.
Choosing the right tool
| Tool | Selects items by | Returns | Fails when |
|---|---|---|---|
| `remove(x)` | value | `None` | `x` is not in the list |
| `pop()` / `pop(i)` | position (default: last) | the removed item | list is empty or `i` is out of range |
| `del lst[i]` / `del lst[i:j]` | position or slice | nothing (it is a statement) | `i` is out of range |
| `clear()` | everything | `None` | never |
All four change the list in place. None of them creates a new list.
remove: delete by value
remove(x) finds the first item equal to x and deletes it. Later duplicates stay.
nums = [1, 2, 3, 2, 4]
nums.remove(2)
print(nums) # [1, 3, 2, 4]
try:
nums.remove(99)
except ValueError as err:
print(err) # list.remove(x): x not in listIf the value might be missing, check first with in, or catch ValueError.
pop: delete by position and keep the item
pop(i) removes the item at index i and returns it. Without an argument it removes the last item. This makes it the usual choice when you need to use the removed value.
nums = [0, 1, 2, 4, 5, 6]
last = nums.pop() # 6
first = nums.pop(0) # 0
print(last, first, nums) # 6 0 [1, 2, 4, 5]
empty = []
try:
empty.pop()
except IndexError as err:
print(err) # pop from empty listRemoving from the end is cheap. Removing from the front shifts every remaining item left, so it costs time proportional to the list length.
del: delete by index or slice
del is a statement, not a method. It removes the item at an index, or a whole slice at once.
nums = [10, 20, 30, 40, 50, 60]
del nums[0] # [20, 30, 40, 50, 60]
del nums[1:3] # [20, 50, 60]
del nums[::2] # [50]
print(nums)Slices are the reason to prefer del over repeated pop calls. One statement removes a range, or every n-th item with an extended slice.
clear: empty the list
clear() removes every item but keeps the same list object. del nums[:] does the same thing.
nums = [1, 2, 3]
alias = nums
nums.clear()
print(alias) # [] because both names refer to the same list
nums = [1, 2, 3]
alias = nums
nums = [] # rebinding: creates a new list
print(alias) # [1, 2, 3]Use clear() when other names or objects hold a reference to the list and must see it emptied. Assigning [] only changes what one name points to.
Removing while looping
Do not remove items from a list while a for loop iterates over it. The loop tracks an index, and deletions shift the items under it, so some items are skipped.
nums = [1, 2, 2, 3, 4]
for n in nums:
if n % 2 == 0:
nums.remove(n)
print(nums) # [1, 2, 3] (one 2 was skipped)Build a filtered list instead, then assign it back if needed.
nums = [1, 2, 2, 3, 4]
nums = [n for n in nums if n % 2 != 0]
print(nums) # [1, 3]To keep the same list object, use slice assignment: nums[:] = [n for n in nums if n % 2 != 0].
Exercise
Given items = ["a", "b", "c", "b", "d"], write code that removes every "b" and leaves items as the same list object, so other names that refer to it see the change. Why does a loop calling items.remove("b") over items itself risk a bug?
Show answer
Use slice assignment: items[:] = [x for x in items if x != "b"]. This keeps the same list object and gives ["a", "c", "d"]. Looping over items while removing from it shifts later items left, so the loop skips the element right after each removal, and adjacent matches can be missed.
Exercise
What does pop return, and what does remove return? What happens if you call [].pop()?
Show answer
pop returns the removed item. remove returns None. [].pop() raises IndexError: pop from empty list.