1
>>> x = {"a","b","c","d","e"}
>>> print x
set(['a', 'c', 'b', 'e', 'd'])

Who can help to explain why the sequence of set elements changed after it is printed out?

-- Update: Thanks guys!

Yes, set is a set of elements, there is no order for "set". but every time you print, the output is the same. Please help explain why the set {"a","b","c","d","e"} was saved as ['a', 'c', 'b', 'e', 'd'] by python, in what kind of order? it seems not in the sequence of ASCII of characters.

-- Update: Paul Rooney's answer is the root cause I want to know. The order of set output relates to the hash of each element in the set which is explained in the official document. Thanks!

The order is dictated by the hashes of the values, the size of the underlying hash table and the number of hash collisions that occurred. See here --Paul Rooney

Haili Sun
  • 621
  • 8
  • 13
  • 5
    Set, inherently, has no **order**. What is it that you want to do exactly? – UltraInstinct May 17 '16 at 23:16
  • 2
    The order is dictated by the hashes of the values, the size of the underlying hash table and the number of hash collisions that occurred. See [here](http://stackoverflow.com/questions/12165200/order-of-unordered-python-sets) – Paul Rooney May 17 '16 at 23:33

2 Answers2

4

check this out: https://docs.python.org/2/library/stdtypes.html#set

sets simply do not have any ordering to them.

David Schuler
  • 1,011
  • 2
  • 10
  • 21
  • That's the wrong documentation. The `sets` module has nothing to do with the `set` type. As the big red notice at the top of the page says, `sets` is deprecated and `set` is its replacement. – user2357112 May 17 '16 at 23:35
  • good call. I updated the link – David Schuler May 17 '16 at 23:36
  • 1
    Better. I recommend linking to [a bit further up the page](https://docs.python.org/2/library/stdtypes.html#set-types-set-frozenset); right now, your link goes to below the part where the documentation says sets are unordered. – user2357112 May 17 '16 at 23:53
3

It's not after the print but after the cast to set that the order is lost.

The set datatype is a unique, unordered list.

jsphpl
  • 4,800
  • 3
  • 24
  • 27