a = 1
b = 1
id(a) == id(b) # True
Here is Python optimize memory consumption and reuse memory for two variables.
c = 1.45
d = 1.45
id(c) == id(d) # False - Why ?
In the case of float Python doesn't use this optimization. Why?
a = 1
b = 1
id(a) == id(b) # True
Here is Python optimize memory consumption and reuse memory for two variables.
c = 1.45
d = 1.45
id(c) == id(d) # False - Why ?
In the case of float Python doesn't use this optimization. Why?
CPython (the reference interpreter), as an implementation detail, has a small int cache for ints between -5 and 256; each value is intended to be unique (not always true in practice, but most of the time it's true; you shouldn't rely on it though).
This makes simple tasks like iterating a bytes object much cheaper (since all the values can be pulled from the cache), and saves some memory for commonly used small int values. It's not dynamically sized though, so creating 257 twice will get different ids (not always, but in many cases; there are other constant caching operations applied during compilation that can collapse such values used as literals in close proximity).
No such cache exists for floats, since there are a nigh infinite number of float values, and few are likely to see reuse across broad swathes of the program.