The official Python 2.7 docs for these methods sounds nearly identical, with the sole difference seeming to be that remove() raises a KeyError while discard does not.
I'm wondering if there is a difference in execution speed between these two methods. Failing that, is there any meaningful difference (barring KeyError) between them?
The discard() method removes the specified item from the set. This method is different from the remove() method, because the remove() method will raise an error if the specified item does not exist, and the discard() method will not.
Note: If the item to remove does not exist, remove() will raise an error.
HashSet 's remove() takes O(1) expected time to locate the element to be removed - the hashCode() takes you to the bin that contains the element, and each bin is expected to have a small number of entries, so finding the element in the bin and removing it should take constant time.
The built-in method, remove() in Python, removes the element from the set only if the element is present in the set, just as the discard() method does but If the element is not present in the set, then an error or exception is raised.
Raising an exception in one case is a pretty meaningful difference. If trying to remove an element from a set that is not there would be an error, you better use set.remove()
rather than set.discard()
.
The two methods are identical in implementation, except that compared to set_discard()
the set_remove()
function adds the lines:
if (rv == DISCARD_NOTFOUND) {
set_key_error(key);
return NULL;
}
This raises the KeyError
. As this is slightly more work, set.remove()
is a teeniest fraction slower; your CPU has to do one extra test before returning. But if your algorithm depends on the exception then the extra branching test is hardly going to matter.
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