all Python 3Sets (set)function
set.remove
removal
Remove an element; raises KeyError if it is absent (unlike discard).
Syntax
s.remove(elem)
A KeyError here means the element was already gone, which is normally a bug in your logic rather than an everyday case — wrapping the call in try/except is a smell, and if absence is expected you want discard. A separate trap is removing items while iterating over the same set: the loop dies with a RuntimeError about the size changing, so iterate over a copy.
Examples
s = {1, 2, 3}
s.remove(2)
print(sorted(s)) # → [1, 3]
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy