Python › Memory Management & Garbage Collection
How does object interning (like small integer caching and string interning) affect memory and identity comparisons?
AdvancedAnswer
CPython caches small integers (-5 to 256) and some string literals as singleton objects, so multiple variables referencing the same small int or interned string may share the same object in memory (verifiable with `is`). This is a memory optimization detail, not a guaranteed language feature -- relying on `is` for value equality of ints or strings outside interning ranges is a common bug source.
a = 100
b = 100
print(a is b) # True -- small int caching
x = 1000
y = 1000
print(x is y) # often False -- not cached, implementation-dependentReal-world example A subtle bug arises when code checks `if user_id is 12345:` instead of `==`, working accidentally in testing due to caching but failing in production with larger, uncached integer values.