Apr-02-2017, 10:11 PM
(Apr-01-2017, 11:00 PM)snippsat Wrote:(Apr-01-2017, 10:27 PM)Nirelg Wrote: They are both int after all, so why when I write twice 2**2 it gives me the same id yet when I do the same for 2**11 it gives them different ids?Integers between -5 and 256 are cached in Python.
This optimization strategy makes sense because small integers pop up all over the place,
and given that each integer takes 24 bytes, it saves a lot of memory for a typical program.
Soid()
show memory address.
>>> help(id) Help on built-in function id in module builtins: id(...) id(object) -> integer Return the identity of an object. This is guaranteed to be unique among simultaneously existing objects. (Hint: it's the object's memory address.) >>> id(10) 491765920 >>> id(10) 491765920 >>> id(10) 491765920 >>> id(100) 491767360 >>> id(100) 491767360 >>> id(100) 491767360 >>> # Now over 256 >>> id(1000) 58284576 >>> id(1000) 51896640
To be honest, when I am doing the same thing you do, I am getting different results...
when I use "**" my program works as it should:
print id(2**8) print id(2**8) print id(2**9) print id(2**9)
Output:44072652
44072652
44819164
44819152
Yet when i write it like this:print id(256) print id(256) print id(512) print id(512)
Output:45252300
45252300
45998848
45998848
Even the ints above 256 have the same id.I tried it both with larger numbers and from cmd with the same result...
any idea why it works like this?