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

← All Python set methods · List methods · list vs tuple vs set