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)
e The element to be removed.

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

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

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

print(myset)

The method does nothing if the method is not present.

myset = {1, 3, 5}

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

print(myset)

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.

myset = {1, 3, 5}

#raises a KeyError exception
myset.remove(4)