Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Set order
#7
(Jan-09-2023, 06:21 PM)deanhystad Wrote: Sets are in hash table order, but hash table order is not fixed, or at least not predictable. I ran this code multiple times:

Set elements in cpython are printed in hash table order unless there is a hash collision between the elements. Then for elements in the same bucket, it prints in insertion order (or perhaps reverse insertion order?)

For a small set like this, there's probably only 8 or 16 hash buckets. So sometimes the "C" and "A" objects are assigned IDs that hash to the same bucket. When that happens, the set("ABC") and set("CBA") will print in a different order.

This is more easily demonstrated with small integers, which have fixed hash IDs. When they don't collide, the print order is fixed. When they do collide, print order changes.

>>> print(set([11, 3]), set([3, 11])) # 3 and 11 share the same final 3 bits
{3, 11} {11, 3}
>>> print(set([12, 3]), set([3, 12])) # 3 and 12 differ in the final 3 bits.
{3, 12} {3, 12}
Reply


Messages In This Thread
Set order - by FreshEire - Jan-09-2023, 05:06 PM
RE: Set order - by deanhystad - Jan-09-2023, 05:25 PM
RE: Set order - by woooee - Jan-09-2023, 06:08 PM
RE: Set order - by deanhystad - Jan-09-2023, 06:21 PM
RE: Set order - by woooee - Jan-09-2023, 06:35 PM
RE: Set order - by deanhystad - Jan-09-2023, 07:18 PM
RE: Set order - by bowlofred - Jan-09-2023, 07:20 PM
RE: Set order - by perfringo - Jan-09-2023, 07:26 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020