简体   繁体   中英

Why does Python print a set of numbers as ordered

I tried print this in the python idle {6,3,7}. The output was {3,6,7}. Shouldn't sets be unordered and print a different order each time? Is it something related to the way hash maps are built?

Sets are indeed unordered in Python. The fact that your particular example set happens to give elements in apparently sorted order when iterated over (and appears reproducible in python 2.7.6 and 3.4.3) does not negate this fact, and another example gives elements in an order which is neither the order in which they were added to the set, nor is it sorted.

>>> list(set([6,3,7]))
[3, 6, 7]

>>> list(set([6,3,8]))
[8, 3, 6]

For the values 6, 3 and 8, the order in which iteration over a python set containing those values will yield elements does at least appear to be consistent, regardless of the order in which the set was populated. However, this says nothing about whether this result is generally true, and in any case it should be considered an implementation detail. User code should not assume any ordering at all.

>>> from sympy.utilities.iterables import multiset_permutations
>>> for p in multiset_permutations([3,6,8]): print(p, list(set(p)))
... 
([3, 6, 8], [8, 3, 6])
([3, 8, 6], [8, 3, 6])
([6, 3, 8], [8, 3, 6])
([6, 8, 3], [8, 3, 6])
([8, 3, 6], [8, 3, 6])
([8, 6, 3], [8, 3, 6])

See, I understand your concern, and I was confused in the beginning as well, when I first saw it. But I am certain you know sets are unordered and unindexed. Hence it cannot be the case that the elements of any set are ordered. Try running something like a = {6,2,90,4,12,0,4000,345} or your example -- on Jupyter Notebook, or on IDLE or through command prompt. It's arranged differently.

On Jupyter, it gave: {0, 2, 4, 6, 12, 90, 345, 4000}

On Command Prompt: {0, 4000, 2, 4, 6, 12, 345, 90}

And when you print the elements of a set one by one, it will be shown in the order:

4000
2
4
6
12
345
90

I believe you were trying on Jupyter. They always seem to sort it when you want to see a variable like a , here.

And for your doubt, hash map concept applies to dictionaries, and not to sets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM