0
x1 = {'foo', 'bar', 'baz'}
x2 = {'baz', 'qux', 'quux'}

a=((x1.union(x2)))
b=(x1 | x2)
print(a)  #{'qux', 'bar', 'quux', 'baz', 'foo'}
print(b)  #{'qux', 'bar', 'quux', 'baz', 'foo'}
# a and b are always printed in a same order

print(a is b)  #false

the order of a and b on each execution will change, but their order are always same when they printed.
as set is unordered I expected the order of a and b on print, should be different.
i have read these 2 associated links, but couldn't find a answer:
Why does a set display in same order if sets are unordered?
Why is the order in dictionaries and sets arbitrary?

armin
  • 19
  • 5
  • 1
    Shouldnt the first link answer the question? – timgeb Feb 10 '22 at 18:17
  • The iteration order (which can be distinct from any underlying *storage* order) is constant for an unmodified object, but subject to randomization to avoid certain kinds of attacks. – chepner Feb 10 '22 at 18:22

1 Answers1

1

Every string gets translated into a number (a hash). Then, when calling a for each procedure on the hash table, the elements are presumably enumerated from the lowest hash to the highest hash. That's why it doesn't matter what order you insert them in and why the order of enumeration for same elements is always the same. There is no intrinsic "randomness" in hashtables, hash computations are deterministic, just like enumeration.

Captain Trojan
  • 2,800
  • 1
  • 11
  • 28