Why can `a is b` sometimes return True for two separately written integer or string literals, and why is relying on this dangerous?
Answer
CPython caches small integers from -5 to 256 and interns many string literals that look like identifiers as a memory and speed optimization, so two separate literals can end up referencing the same cached object and `is` returns True by coincidence. This behavior is a CPython implementation detail, not a language guarantee: it can change between versions or contexts (for example, values built at runtime via concatenation or string formatting are usually not interned), so code should always use `==` for value comparisons and reserve `is` for identity checks against singletons like `None`.
Strong answer includes
- small-int cache and string interning are implementation details
- not guaranteed across versions or code paths
- use == for values, is only for singleton identity
Practical example
x = 200; y = 200; x is yis often True due to integer caching, but
x = 2000; y = 2000; x is yis typically False because 2000 falls outside the cached range.