pythonpython-3.xsetpython-3.9unordered

Why are python sets "sorted" in ascending order?


Let's run the following code:

st = {3, 1, 2}
st
>>> {1, 2, 3}
st.pop()
>>> 1
st.pop()
>>> 2
st.pop()
>>> 3

Although sets are said to be unordered, this set behaves as if it was sorted in ascending order. The method pop(), that should return an 'arbitrary element', according to the documentation, returns elements in ascending order as well. What is the reason for this?


Solution

  • The order correlates to the hash of the object, size of the set, binary representation of the number, insertion order and other implementation parameters. It is completely arbitrary and shouldn't be relied upon:

    >>> st = {3, 1, 2,4,9,124124,124124124124,123,12,41,15,}
    >>> st
    {1, 2, 3, 4, 9, 41, 12, 15, 124124, 123, 124124124124}
    >>> st.pop()
    1
    >>> st.pop()
    2
    >>> st.pop()
    3
    >>> st.pop()
    4
    >>> st.pop()
    9
    >>> st.pop()
    41
    >>> st.pop()
    12
    >>> {1, 41, 12}
    {1, 12, 41}
    >>> {1, 9, 41, 12}
    {1, 12, 9, 41}  # Looks like 9 wants to go after 12.
    >>> hash(9)
    9
    >>> hash(12)
    12
    >>> hash(41)
    41
    >>> {1, 2, 3, 4, 9, 41, 12}
    {1, 2, 3, 4, 9, 12, 41}  # 12 before 41
    >>> {1, 2, 3, 4, 9, 41, 12, 15}  # add 15 at the end
    {1, 2, 3, 4, 9, 41, 12, 15}  # 12 after 41