Immutable Primitives: int, float, str, tuple & Small Integer Caching
1Concept
In Python, primitives are immutable. CPython pre-allocates an array of small integer singleton objects for values from -5 to 256. Any integer created within this range shares the exact same memory address (`id()`). Tuples are immutable sequence objects whose memory cannot be resized.
2Architecture Diagram
CPython Small Int Cache Array (-5 to 256):
a = 100 ---
\---> [ Singleton PyLongObject (100) at 0x7FFF00 ] (Shared in memory!)
b = 100 ---/
c = 500 ---> [ PyLongObject at 0x1000 ]
d = 500 ---> [ Separate PyLongObject at 0x2000 ]3Code Example
Python 3.12
a = 250
b = 250
print(f"a is b (-5 to 256 cached): {a is b}")
x = 1000
y = 1000
print(f"x is y (Outside cache): {x is y}")
# Immutable string modification creates new object
text = "Enterprise"
original_id = id(text)
text += " Python"
print(f"String ID changed after modification: {original_id != id(text)}")4Expected Output
a is b (-5 to 256 cached): True x is y (Outside cache): False String ID changed after modification: True
5Key Takeaways
- ✓CPython caches integers between -5 and 256 as immortal/singleton objects.
- ✓`is` tests memory address identity (`id(a) == id(b)`); `==` tests value equality.
- ✓A tuple is immutable, but if it holds a mutable list, that inner list can still be modified.