Understanding the set() function

前端 未结 5 789
故里飘歌
故里飘歌 2020-11-29 02:07

In python, set() is an unordered collection with no duplicate elements. However, I am not able to understand how it generates the output.

For example,

5条回答
  •  生来不讨喜
    2020-11-29 02:14

    As an unordered collection type, set([8, 1, 6]) is equivalent to set([1, 6, 8]).

    While it might be nicer to display the set contents in sorted order, that would make the repr() call more expensive.

    Internally, the set type is implemented using a hash table: a hash function is used to separate items into a number of buckets to reduce the number of equality operations needed to check if an item is part of the set.

    To produce the repr() output it just outputs the items from each bucket in turn, which is unlikely to be the sorted order.

提交回复
热议问题