Skip to main content
  1. Posts/

Why id(1) == id(2-1)?

··133 words·1 min·

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 id
  • id() 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 variable var with value 1, and the expression 2-1 point to the same object.
  • Integers are immutable, so sharing the same instance is safe.
  • Don’t rely on is to compare numeric values; use == to compare for equality. is should 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.
Juan Pedro Bretti Mandarano
Author
Juan Pedro Bretti Mandarano