Python Set remove() vs discard() Explained
Python provides two built-in methods to delete elements from a set:
remove() and discard(). While both methods
delete a specified item from a set in place, their behavior differs
fundamentally when the target element does not exist. The
remove() method raises a KeyError if the
element is absent, whereas the discard() method suppresses
the error and leaves the set unchanged.
The remove() Method
The remove() method deletes a specified element from a
set. If the element is present, it is deleted. If the element is not
found, Python raises a KeyError.
fruits = {"apple", "banana", "cherry"}
# Removing an existing element
fruits.remove("banana")
print(fruits) # Output: {'apple', 'cherry'}
# Attempting to remove a non-existing element
fruits.remove("orange") # Raises KeyError: 'orange'Use remove() when:
- The absence of the element indicates an unexpected state or bug in your program.
- You want explicit error handling using a
try-exceptblock.
The discard() Method
The discard() method also deletes a specified element
from a set. However, if the element is not present, it performs no
action and raises no exception.
fruits = {"apple", "banana", "cherry"}
# Discarding an existing element
fruits.discard("banana")
print(fruits) # Output: {'apple', 'cherry'}
# Attempting to discard a non-existing element
fruits.discard("orange")
print(fruits) # Output: {'apple', 'cherry'} (No error raised)Use discard() when:
- You want to ensure an item is absent from the set regardless of whether it was there initially.
- You want cleaner, more concise code without wrapping operations in
try-except KeyErrorblocks.
Key Differences Summary
| Feature | remove() |
discard() |
|---|---|---|
| Action on existing item | Removes the item | Removes the item |
| Action on missing item | Raises KeyError |
Does nothing (silent failure) |
| Return value | None |
None |
| Time complexity | \(O(1)\) average | \(O(1)\) average |
| Best suited for | Strict data validation | Idempotent cleanup operations |