7

Why int variable id's in python 2.7 are equal only until 256 ?

For example:

>>> y = 256
>>> m = 256
>>> m is y
True
>>> y = 257
>>> m = 257
>>> id(m)
16282096
>>> id(y)
16281952
>>> m is y
False
Saeed Ghareh Daghi
  • 1,164
  • 1
  • 13
  • 21
  • 3
    Implementation detail; small integers are interned (made singletons) as a tradeoff between performance and memory footprint. – Martijn Pieters Feb 19 '16 at 15:33
  • 2
    The range is `-5 to 256` including (-5 and 256). This is done for performance optimization. – Akavall Feb 19 '16 at 15:34
  • http://www.laurentluce.com/posts/python-integer-objects-implementation/ – dan-man Feb 19 '16 at 15:37
  • 2
    PyObject* PyInt_FromLong(long ival) Return value: New reference. Create a new integer object with a value of ival. The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object. So it should be possible to change the value of 1. I suspect the behaviour of Python in this case is undefined. :-) – Saeed Ghareh Daghi Feb 19 '16 at 15:38
  • It's really irrelevant. You shouldn't use `id` in the first place. – Karoly Horvath Feb 20 '16 at 14:09

0 Answers0