Skip to content

Instantly share code, notes, and snippets.

@qlixed
Created August 25, 2017 20:42
Show Gist options
  • Save qlixed/33766b03ea6bdddc04f9ed1e2ebcbf21 to your computer and use it in GitHub Desktop.
Save qlixed/33766b03ea6bdddc04f9ed1e2ebcbf21 to your computer and use it in GitHub Desktop.
Python integer particularities in CPython
In [1]: a = 1
In [2]: b = 1
In [3]: a is b
Out[3]: True
In [4]: id(a)
Out[4]: 140720033629792
In [5]: id(a) == id(b) == id(1)
Out[5]: True
In [6]: # Let's check 0:
In [7]: a = 0
In [8]: b = 0
In [9]: id(a)
Out[9]: 140720033629760
In [11]: id(a) == id(b) == id(0)
Out[11]: True
In [12]: # Check further:
In [13]: c=256
In [14]: id (c)
Out[14]: 140720033637952
In [15]: id(c)-id(a) # That particular number..??
Out[15]: 8192
In [16]: # Mmmm.. wait a minute!
In [17]: import sys
In [18]: print(sys.int_info)
sys.int_info(bits_per_digit=30, sizeof_digit=4)
In [19]: # sizeof_digit = 4 means 4 bytes, so 32 bits!
...: # I get it!, now:
...: (id(c)-id(a))/(sys.int_info.sizeof_digit*8) # 8 bits = 1 byte
Out[19]: 256.0
In [20]: # WAAAA!. Check one more:
...: c = 257
In [21]: d = 257
In [22]: c is d
Out[22]: False
In [23]: id(c)
Out[23]: 140719783347216
In [24]: id(c) == id(d)
Out[24]: False
In [25]: (id(c)-id(a))/(sys.int_info.sizeof_digit*8) # 8 bits = 1 byte
Out[25]: -7821329.5
In [26]: #Uh... ok, not what anyone expect right?
...: #So, from -5 to 256 values are
...: # preloaded in a contiguous table in memory (Integer singletons)
...: #This is done by implementation in CPython
...: # for optimization purposes.
In [33]: # You can check more of this here:
...: # For ints:
...: # https://docs.python.org/2/c-api/int.html#c.PyInt_FromLong
...: # https://docs.python.org/3.7/c-api/long.html?highlight=pylong#c.PyLong_FromLong
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment