I have a code for discard and remove function in Python 3. Can anyone explain the difference?
remove() function :
num_set = set([0, 1, 2, 3, 4, 5])
num_set.remove(0)
print(num_set)
o/p
{1, 2, 3, 4, 5}
discard() function :
num_set = set([0, 1, 2, 3, 4, 5])
num_set.discard(3)
print(num_set)
o/p:
{0, 1, 2, 4, 5}
From docs:
remove(elem): Remove elementelemfrom the set. Raises KeyError ifelemis not contained in the set.
discard(elem): Remove elementelemfrom the set if it is present.
That is: remove raises an error, discard not.
It is useful to refer to the documentation:
remove(elem)
Remove element elem from the set. Raises KeyError if elem is not contained in the set.discard(elem)
Remove element elem from the set if it is present.
One of them will raise an exception when the element is not present, the other does not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With