3

As explained in Can Python's set absence of ordering be considered random order?, the set structure is in arbitrary order. For example, the following code results in different output between runs.

idList = [ "ID" + str(i) for i in range(10) ]*10
idSet = set(idList)
print(idSet)

I would like to understand what internally causes this unpredictable behaviour. Why does the same code and input produce different output? Is it dependent on the memory addresses used by Python, the availability of data in some cache or does for example the implementation/algorithm include some random elements?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
jpf
  • 65
  • 4
  • 3
    maybe you can find some clue from [set's implementation](https://github.com/python/cpython/blob/main/Objects/setobject.c). – Lei Yang Feb 15 '22 at 08:30
  • 5
    See https://stackoverflow.com/a/27522708/3001761 - if you disable hash randomisation you can see you _do_ get the same result between runs. – jonrsharpe Feb 15 '22 at 08:39
  • Thank you! Random hash seed explains it clearly! – jpf Feb 15 '22 at 08:53

0 Answers0