16

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?

Akshat Mahajan
  • 8,850
  • 3
  • 34
  • 43
  • Related post on similar lines for list data structure - [Difference between del, remove and pop on lists](https://stackoverflow.com/q/11520492/465053) – RBT Aug 01 '18 at 02:52

1 Answers1

33

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.

Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187