Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

set.remove

Removes a required member from a set.

Version: Python 3.14; repository image, production runtime not attested

Syntax

s.remove(element, /)

Removes a required member from a set.

A second attempt to remove the same member raises KeyError unless it was inserted again.

The first call finds 3, removes it from the same set and returns None. The next call cannot find 3 and raises KeyError. Catching that exception leaves {2} available for the final print. Choose discard when absence is an acceptable outcome.

s = {1, 2}
assert s.remove(2) is None and s == {1}

Examples

s = {2, 3}
s.remove(3)
try:
    s.remove(3)
except KeyError as error:
    print(type(error).__name__)
print(sorted(s))

Result

KeyError
[2]

The first call finds 3, removes it from the same set and returns None. The next call cannot find 3 and raises KeyError. Catching that exception leaves {2} available for the final print. Choose discard when absence is an acceptable outcome.

Sources