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

后端 未结 1 1105
孤独总比滥情好
孤独总比滥情好 2020-12-14 22:54

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.

<
相关标签:
1条回答
  • 2020-12-14 22:56

    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.

    0 讨论(0)
提交回复
热议问题