set.discard
Remove an item from the set if it is present.
Python 3.13
set.discard(elem)Parameters
- elemHashable
- The item to remove.
Return value
Nothing (None); the set is changed in place, with no error if the item is missing.
Examples
Removing a missing item without an error
Python 3.13
s = {1, 2, 3}
s.discard(4)
print(s){1, 2, 3}Removing an existing item
Python 3.13
s = {1, 2, 3}
s.discard(2)
print(s){1, 3}Details
Unlike set.remove, it does not raise KeyError, so there is no need to check for the item first. An unhashable argument, such as a list, still raises TypeError.
