Memory Modelmedium

Object Interning

Python reuses the same object for small integers (-5 to 256) and some strings instead of creating new ones.

Memory anchor

interning = a hotel giving everyone asking for Room 42 the SAME key. Small integers (-5 to 256) are permanent hotel residents — everyone shares their key. Big numbers get a fresh room each time.

Expected depth

Integers from -5 to 256 are pre-allocated singletons — a is b is True for these. Strings that look like identifiers (alphanumeric, underscore) are often interned automatically. sys.intern(s) forces string interning. This is an implementation detail of CPython, not guaranteed by the language spec.

Deep — senior internals

Integer interning is a startup-time optimization: CPython pre-allocates 262 integer objects. For strings, CPython interns compile-time string constants that look like identifiers. Runtime strings (e.g., built by concatenation) are typically NOT interned. This matters for performance when doing many string equality checks — interned strings use is (pointer comparison) rather than character-by-character comparison. The interning cache for strings is a dict in the interpreter state.

🎤Interview-ready answer

Python interns small integers (-5 to 256) and identifier-like strings — reusing the same object instead of creating duplicates. This means 'a is b' can be True for small ints and compile-time strings even without explicit assignment. It's a CPython implementation detail, not a language guarantee. sys.intern() forces a string into the intern table. The practical implication: always use == for value comparison, never rely on is for strings or ints outside the known range.

Common trap

a = 1000; b = 1000; a is b may be True or False depending on context — Python may or may not optimize this. Never use is to compare integers or strings for value equality. Always use ==.

Related concepts