Why python set displays in “same” order if sets are unordered?

旧街凉风 提交于 2020-07-01 14:38:41

问题


I'm taking a first look at the python language from Python wikibook.

For sets the following is mentioned - We can also have a loop move over each of the items in a set. However, since sets are unordered, it is undefined which order the iteration will follow.

and the code example given is

s = set("blerg")

for letter in s:
     print letter

Output:

 r b e l g

When I run the program I get the results in the same order, no matter how many times I run. If sets are unordered and order of iteration is undefined, why is it returning the set in the same order ? and what is the basis of the order ?

[PS: Excuse me if I have misunderstood something very basic. I'm a python newbie]


回答1:


They are not randomly ordered, they are arbitrarily ordered. It means you should not count on the order of insertions being maintained as the actual internal implementation details determine the order instead.

The order depends on the insertion and deletion history of the set.

In CPython, sets use a hash table, where inserted values are slotted into a sparse table based on the value returned from the hash() function, modulo the table size and a collision handling algorithm. Listing the set contents then returns the values as ordered in this table.

If you want to go into the nitty-gritty technical details then look at Why is the order in dictionaries and sets arbitrary?; sets are, at their core, dictionaries where the keys are the set values and there are no associated dictionary values. The actual implementation is a little more complicated, as always, but that answer will suffice to get you most of the way there. Then look at the C source code for set for the rest of those details.

Compare this to lists, which do have a fixed order that you can influence; you can move items around in the list and the new ordering would be maintained for you.



来源:https://stackoverflow.com/questions/21701618/why-python-set-displays-in-same-order-if-sets-are-unordered

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!