Skip to content
LakeBench
ProblemsCommunityPricing
Sign inStart practicing
Back
  1. Home
  2. Interview prep
  3. What is interning?

Python · Memory & Internals

What is interning?

Hardpython-33
interningstringsintegersidentitymemory

Question

What is string/integer interning in Python?

Solution

Interning stores one canonical copy of certain immutable values and reuses that object for equal values. Identity (is) may then succeed even for separately spelled literals, but that is an optimization, not a language guarantee. Do not build business logic on it.

Strings

  • Some identifiers/literals may be automatically interned.
  • sys.intern(s) forces internment (useful for many repeated dict keys).

Integers

  • CPython caches a range of small integers (commonly -5..256). Those share identity.
  • Larger integers are not reliably cached.
import sys

a = "pipeline"
b = "pipeline"
print(a is b)  # often True for literals (implementation detail)

x = sys.intern("user:" + "42")
y = sys.intern("user:42")
print(x is y)  # True

print(256 is 256)    # True (small int cache)
print((256 + 1) is (257))  # may be False for computed values
print(257 == 257)    # always compare with ==

Interview rule: Explain interning as a memory/speed optimization; always compare values with == unless checking singletons like None.

🎯 Put this concept into practice

Solidify this answer with real hands-on interview drills in the browser studio.

Open related drill →
PreviousNext