A set
represents a collection of unordered, unique elements.
Sets are mutable meaning that
The discard()
method is used to
myset.discard(e)
e |
The element to be removed. |
The discard()
method removes element e if it exists in the set, otherwise
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 thatremove()
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)