The official Python documentation describes set.discard(elem) as:
Remove element elem from the set if it is present.
and set.remove(elem) as:
Remove element elem from the set. Raises KeyError if elem is not contained in the set.
Hence, it is obvious that both the functions do the same work, but differ only with throwing an error for an absent key. As we already had the infrastructure for set.remove, it was easy to base and implement set.discard on top of that.
The idea is simple - utilize the same back-end function, but do not throw an error for set.discard.
The official Python documentation describes
set.discard(elem)
as:and
set.remove(elem)
as:Hence, it is obvious that both the functions do the same work, but differ only with throwing an error for an absent key. As we already had the infrastructure for
set.remove
, it was easy to base and implementset.discard
on top of that.The idea is simple - utilize the same back-end function, but do not throw an error for
set.discard
.Working
The changed length and KeyError for
set.remove
prove the normal working ofset.discard
.Handling KeyError
set.discard
set.remove