Python 3 reference · Set Methods

Python Set remove() Method

Remove an element from the set. Raises KeyError if it isn't present; use discard() to avoid the error.

Python 3 Since 3.0

Syntax

set.remove(elem)

Parameters

ParameterDescription
elem The element to remove.

Return value

None.

Examples

Remove an elementTry it yourself
s = {"a", "b"}
s.remove("a")
print(s)

Output

{'b'}
Missing elements raise KeyErrorTry it yourself
s = {"a"}
try:
    s.remove("z")
except KeyError as e:
    print("KeyError:", e)

Output

KeyError: 'z'

Version history

VersionChange
Python 3.0Added