How is set() implemented?

后端 未结 6 1736
旧时难觅i
旧时难觅i 2020-11-22 15:07

I\'ve seen people say that set objects in python have O(1) membership-checking. How are they implemented internally to allow this? What sort of data structure d

6条回答
  •  时光取名叫无心
    2020-11-22 15:40

    According to this thread:

    Indeed, CPython's sets are implemented as something like dictionaries with dummy values (the keys being the members of the set), with some optimization(s) that exploit this lack of values

    So basically a set uses a hashtable as its underlying data structure. This explains the O(1) membership checking, since looking up an item in a hashtable is an O(1) operation, on average.

    If you are so inclined you can even browse the CPython source code for set which, according to Achim Domma, is mostly a cut-and-paste from the dict implementation.

提交回复
热议问题