Sets don’t make any promises about the ordering of their members. They use hashing, which itself is an implementation detail of the Python interpreter and depends on multiple factors.
To avoid hash collisions, which is a well-known security exploit, Python chooses a random seed for the hash function every time it starts. As a result, the same object will produce different and seemingly random hash values in separate interpreter sessions:
$ python
>>> hash('Archi')
-863196821531266440
$ python
>>> hash('Archi')
4042034065582253111
$ python
>>> hash('Archi')
7069460679375787308
These numbers determine the order of your set members. If you’re aware of the risks involved, you can disable this mechanism, for example, by setting an environment variable:
$ PYTHONHASHSEED=123 python
>>> hash('Archi')
1934745164520175339
$ PYTHONHASHSEED=123 python
>>> hash('Archi')
1934745164520175339
$ PYTHONHASHSEED=123 python
>>> hash('Archi')
1934745164520175339
Then, you should be able to get a predictable order of set members. However, if you need them to retain insertion order, you’re better off using a different collection such as OrderedSet:
$ pip install orderedset
$ python
>>> from orderedset import OrderedSet
>>> oset = OrderedSet([1, 2, 3])
OrderedSet([1, 2, 3])
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4