Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Runtime difference between set.discard and set.remove methods in Python?

Tags:

python

set

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?

like image 443
Akshat Mahajan Avatar asked Jan 08 '15 21:01

Akshat Mahajan


People also ask

What is the difference between discard and remove in set Python?

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.

Which method will raise an error while removing an element that does not exist in a set?

Note: If the item to remove does not exist, remove() will raise an error.

Is set remove O 1?

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.

What is the difference between Remove and discard in set?

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.


1 Answers

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.

like image 189
Martijn Pieters Avatar answered Oct 16 '22 03:10

Martijn Pieters