add-remove
set.discard
Removes an element from the set if it is present, and does nothing otherwise. Unlike remove(), never raises an error.
s.discard(elem) Parameters
| Parameter | Purpose |
|---|---|
| elem | The element to remove if present |
| returns | None — silent when element is absent |
Examples
>>> s = {1, 2, 3}
>>> s.discard(2)
>>> s
{1, 3} Removes the element.
>>> s = {1, 2, 3}
>>> s.discard(99)
>>> s
{1, 2, 3} No error for missing element.
>>> s = {'x', 'y'}
>>> s.discard('z')
>>> s.discard('x')
>>> s
{'y'} Safe to call unconditionally.
>>> s = set()
>>> s.discard(1)
>>> s
set() Works on empty sets without error.
Gotcha
discard is silent on missing elements — use remove() when you WANT the KeyError to signal a bug.
Related methods
set.remove
Removes the specified element from the set. Raises KeyError if the element is not present.
set.pop
Removes and returns an arbitrary element from the set. Raises KeyError if the set is empty.
set.clear
Removes all elements from the set, leaving it empty. Mutates the set in place; other references to the same set see it emptied.
set.add
Adds a single hashable element to the set in place. If the element is already present, the set is unchanged (no error).
set.update
Adds every element from each iterable argument to s in place. Equivalent to a union but mutates s instead of returning a new set.
← All Python set methods · List methods · list vs tuple vs set