set.remove() / .discard()
Python · Sets
Theory
Both methods delete one item from a set in place and return None, and both are O(1) on average because the item is found by its hash. The difference is what happens when the item is not there. .remove(item) raises KeyError, which is useful when a missing item means something went wrong. .discard(item) silently does nothing, which is convenient when you just want to make sure the item is gone.
With cities = {'Mumbai', 'Delhi'}, cities.discard('Pune') leaves the set unchanged with no error, while cities.remove('Pune') raises KeyError: 'Pune'. A third option, .pop(), removes and returns an arbitrary item (raising KeyError on an empty set), since sets have no 'last' item. As with lists, never remove items from a set while looping over that same set; Python raises RuntimeError because the set changed size during iteration. Loop over a copy instead: for c in set(cities).
Why we use it
Removing a value, such as an unsubscribed user or a resolved ticket, is routine. Having both methods lets you choose between strict behaviour that catches mistakes and forgiving behaviour that keeps code simple.
When to use it
Use discard() when the item may or may not be present and that is fine. Use remove() when absence would be a bug you want to notice. To remove many items, use difference_update() or the -= operator.
How it works
- Call cities.discard('Pune') or cities.remove('Pune')
- Compute hash('Pune') and look in that slot
- Is 'Pune' in the set? Yes: Delete it and return None. No: Go to the next check.
- Was remove() used? Yes: Raise KeyError: 'Pune'. No: discard() returns None silently.
- The set no longer contains 'Pune'
Syntax
set.remove(item)
set.discard(item)Example
cities = {'Mumbai', 'Delhi'}
cities.discard('Pune') # no error even though absent
print(cities)Key points
- Prefer discard() when you're not sure the item exists
- remove() raises a KeyError on a missing item
- Both return None and run in O(1) on average
- pop() removes an arbitrary item, since sets are unordered
- Do not modify a set while looping over it; loop over a copy