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

2
  • 5
    Set, inherently, has no order. What is it that you want to do exactly? Commented May 17, 2016 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 Commented May 17, 2016 at 23:33

2 Answers 2

4

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

sets simply do not have any ordering to them.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
good call. I updated the link
Better. I recommend linking to a bit further up the page; right now, your link goes to below the part where the documentation says sets are unordered.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.