I just found out that python set order is arbitrary today and I am surprised by that fact. I have always thought the underlying implementation of set
and dict
were very similar, both as hash table. The major difference I thought was that dict
has a value for each key while set
doesn't. So the order would be different from how elements are inserted but deterministic.
Until I found it's not true for set
.
$ cat ht_order.py
colors = ['blue', 'red', 'green', 'yellow']
print(set(colors))
print(dict((c, c) for c in colors))
Run it in the terminal:
$ python3 ht_order.py
{'red', 'yellow', 'blue', 'green'}
{'blue': 'blue', 'red': 'red', 'green': 'green', 'yellow': 'yellow'}
$ python3 ht_order.py
{'yellow', 'blue', 'green', 'red'}
{'blue': 'blue', 'red': 'red', 'green': 'green', 'yellow': 'yellow'}
$ python3 ht_order.py
{'green', 'yellow', 'red', 'blue'}
{'blue': 'blue', 'red': 'red', 'green': 'green', 'yellow': 'yellow'}
Why does set
order keep changing?
EDIT:
Tried running in python2 and I got the same result every time.
$ python2 ht_order.py
set(['blue', 'green', 'yellow', 'red'])
{'blue': 'blue', 'green': 'green', 'yellow': 'yellow', 'red': 'red'}