A set represents a collection of unordered, unique elements.

Sets are mutable meaning that they can be modified by adding or removing elements after they are created.

The discard() method is used to remove an element from a set if it is present.

myset.discard(e)
copy
e The element to be removed.

The discard() method removes element e if it exists in the set, otherwise it does nothing.

ExampleEdit & Run
myset = {1, 3, 4, 5, 7, 8, 9}

#remove elements
myset.discard(4)
myset.discard(8)

print(myset)
copy
Output:
{1, 3, 5, 7, 9} [Finished in 0.011682090349495411s]

The method does nothing if the method is not present.

ExampleEdit & Run
myset = {1, 3, 5}

#with an element that does no exist
myset.discard(6)

print(myset)
copy
Output:
{1, 3, 5} [Finished in 0.011151015758514404s]

discard() vs remove()

The set class also includes the remove() method which works similarly to discard() except that remove() will raise an error if the element does not exist in the set, whereas discard() will not.

The remove() method raises a KeyError exception if the input element dose not exist in the set.

ExampleEdit & Run
myset = {1, 3, 5}

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