4 ms·
that only works for small numbers. I suspect it's a side effect of the small integer cache CPython maintains [0] >>> for x in {2, 1, 3}: print(x) 1
by evil-olive 4y ago
that only works for small numbers. I suspect it's a side effect of the small integer cache CPython maintains [0]
>>> for x in {2, 1, 3}: print(x)
1
2
3
>>> for x in {20, 10, 30}: print(x)
10
20
30
>>> for x in {200, 100, 300}: print(x)
200
100
300
0: https://stackoverflow.com/questions/15171695/whats-with-the-integer-cache-maintained-by-the-interpreter https://stackoverflow.com/questions/15171695/whats-with-the-...
- kevincox 4y agoMy guess is that it is because for int `x == hash(x)`. This means that if your integers are smaller than the number of buckets in the hashtable they will fall into buckets in order and the iteration is likely just over the buckets. For example you can see that by adding a large power of two to the numbers you can see that they are sorted by the remainder (as it seems that the default number of buckets is a power of two): > for x in {2048 + 1, 256 + 3, 1024 + 2, 512 + 4}: print(x) 2049 1026 259 516
- cmcconomy 4y agoright, python caches ints from -5 to 256 as singletons, so id(x) for those numbers is constant. whereas each time you run id() on a number outside that range you will get a different id as a new object is instantiated
- kevincox 4y agoI don't think this is related. `set()` uses `hash(x)` it doesn't care what `id(x)` is. The example I provided works equally well with small numbers and large numbers.