add-remove
set.remove
Removes the specified element from the set. Raises KeyError if the element is not present.
s.remove(elem) Parameters
| Parameter | Purpose |
|---|---|
| elem | The element to remove |
| returns | None — mutates in place; raises KeyError on miss |
Examples
>>> s = {1, 2, 3}
>>> s.remove(2)
>>> s
{1, 3} Element removed successfully.
>>> s = {1, 2, 3}
>>> s.remove(9)
KeyError: 9 Raises KeyError when element is absent.
>>> s = {'a', 'b'}
>>> s.remove('a')
>>> s
{'b'} Works with any hashable type.
>>> s = {1, 2}
>>> if 3 in s: s.remove(3)
>>> s
{1, 2} Guard with 'in' to avoid KeyError, or use discard().
Gotcha
remove() raises KeyError if the element is missing — use discard() when absence is fine. Both take exactly one element.
Related methods
set.discard
Removes an element from the set if it is present, and does nothing otherwise. Unlike remove(), never raises an error.
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