
Why id(1) == id(2-1)?#
var = 1
print(id(var)) # e.g. 9793088
print(id(1)) # same id
print(id(2-1)) # same id
print(id(2)) # different idid()returns the identity of the object (in CPython it’s usually the memory address).- CPython has caching/interning for small integers (by default -5 to 256). Those objects are created once and reused, which is why
1, the variablevarwith value1, and the expression2-1point to the same object. - Integers are immutable, so sharing the same instance is safe.
- Don’t rely on
isto compare numeric values; use==to compare for equality.isshould only be used to compare identity (for example,is None).
Key takeaway#
Python is an incredibly powerful language, but knowing these details helps you avoid hard-to-find bugs.
Also published on LinkedIn.
