10.5 Removing Elements
The four ways to remove items from a list -- remove() by value, pop() by index (which returns what it removes), clear() to empty it, and the del statement, including deleting an entire slice at once.
remove()
Removes the first occurrence of a given value (not a position) — raises ValueError if the value isn’t present.
>>> l = [1, 2, 3, 2, 1]
>>> l.remove(2) # removes the first '2' only
>>> l
[1, 3, 2, 1]
pop()
Removes and returns the element at a given index (default: the last one) — the only removal method that gives the removed value back.
>>> popped = l.pop() # removes and returns the last element
>>> popped, l
(1, [1, 3, 2])
>>> l.pop(0) # remove and return by specific index
1
clear()
Empties the list completely, in place — the list object still exists (same id()), just with zero elements.
>>> l2 = [1, 2, 3]
>>> l2.clear()
>>> l2
[]
del
A statement (not a method) that removes an item by index — or, combined with a slice, an entire range at once.
>>> l3 = [1, 2, 3, 4, 5]
>>> del l3[0]
>>> l3
[2, 3, 4, 5]
>>> del l3[1:3] # delete by slice
>>> l3
[2, 5]
Quick Interview Answer
“Four tools cover removal, and the interview-relevant distinction is what each one identifies and returns:
remove(value)finds by value and raisesValueErrorif absent;pop(index)finds by position, defaults to the last element, and is the only one that hands back what it removed;clear()empties the list entirely while keeping the same object identity; anddelis a statement, not a method, that can remove a single index or — combined with a slice — an entire range in one step.”
Common Mistakes
- Calling
l.remove(x)expecting it to remove by index — it removes by value;l.remove(2)removes the value2, not the element at index2. - Not catching
ValueErrorwhen the value passed toremove()might not be present — checkif x in lfirst, or wrap intry/except. - Forgetting
pop()with no argument removes the last element, not the first —pop(0)is needed to remove and return the first one, and that call is O(n) (see 10.13 Performance).
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form