The set represents an unordered collection of unique elements. Sets are mutable meaning that they can be modified by adding or removing elements once they are created.

The remove()  method is used to remove a specified element from the set if present. It raises a KeyError if the element does not exist.

Syntax:
myset.remove(x)
copy
x The element to be removed.
ExampleEdit & Run
myset = {0, 2, 3, 4, 6, 7, 8, 9}
myset.remove(3)
myset.remove(7)
myset.remove(9)

print(myset)
copy
Output:
{0, 2, 4, 6, 8} [Finished in 0.010335741098970175s]

As mentioned above, a KeyError exception will be raised if the element to be removed is not present in the set.

ExampleEdit & Run
myset = {0, 2, 4, 6}

#raises a KeyError exception
myset.remove(3)
copy
Output:
Traceback (most recent call last):   File "<string>", line 4, in <module> KeyError: 3 [Finished in 0.009815218858420849s]

remove() vs discard()

The set class also includes the discard() method which is similar to the remove() method. The only difference is that the discard() method simply does  not raise any exception if the element to be removed does not exist, it just does nothing.

ExampleEdit & Run
myset = {0, 2, 4, 6, 7}

myset.discard(3)
myset.discard(5)
myset.discard(7)

print(myset)
copy
Output:
{0, 2, 4, 6} [Finished in 0.009814498946070671s]