Dec-29-2021, 01:37 PM
Hey everyone.
This is my first post here. I tried searching a bit on google and couldn't find a post related to this. I'm assuming it's been asked before, but I had no lucking finding anything about it.
There's this peculiar pattern when printing out sets. I'm aware sets don't preserve insertion order like dicts do, and I assume that it's moreso the print function that causes this than the internal implementation of sets? I don't know much C and so I didn't check out setobject.c.
For instance, this code:
I was thinking that maybe the print function prints the items in ascending order based on hash-value, but as far as I'm aware small int's hash is equal to their value. So if that were the case all rows should be in order.
Could anyone please shed some light into what causes this weird pattern?
This is my first post here. I tried searching a bit on google and couldn't find a post related to this. I'm assuming it's been asked before, but I had no lucking finding anything about it.
There's this peculiar pattern when printing out sets. I'm aware sets don't preserve insertion order like dicts do, and I assume that it's moreso the print function that causes this than the internal implementation of sets? I don't know much C and so I didn't check out setobject.c.
For instance, this code:
sets = [set(range(i, i + 10)) for i in range(0, 100, 10)] for s in sets: print(s)yield this result
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} {10, 11, 12, 13, 14, 15, 16, 17, 18, 19} {20, 21, 22, 23, 24, 25, 26, 27, 28, 29} {32, 33, 34, 35, 36, 37, 38, 39, 30, 31} {40, 41, 42, 43, 44, 45, 46, 47, 48, 49} {50, 51, 52, 53, 54, 55, 56, 57, 58, 59} {64, 65, 66, 67, 68, 69, 60, 61, 62, 63} {70, 71, 72, 73, 74, 75, 76, 77, 78, 79} {80, 81, 82, 83, 84, 85, 86, 87, 88, 89} {96, 97, 98, 99, 90, 91, 92, 93, 94, 95}Since set's don't preserve order I find it weird how most of these are printed in order, and those who aren't still follow a pattern; They are shifted to the left by two positions for each row that is out of order. E.g: the 3x's are shifted 2 positions to the lft. The 6x's are shifted 4 positions (2 more than 3xs)
I was thinking that maybe the print function prints the items in ascending order based on hash-value, but as far as I'm aware small int's hash is equal to their value. So if that were the case all rows should be in order.
Could anyone please shed some light into what causes this weird pattern?