The Secret Life of Python: The Statue in the Memory
Source: Dev.to
Demonstrating Aliasing with Strings
The afternoon sun cut through the dust motes dancing in the library air. Timothy felt confident after mastering the Name Tag concept. He wanted to show Margaret what he had learned.
“Watch this,” Timothy said, turning his laptop toward her. “I’ll make two tags,
greeting_oneandgreeting_two. They point to the same string object. Then I’ll modify one and prove that the other changes too.”
greeting_one = "Hello"
greeting_two = greeting_one
# Timothy's plan: modify the object via the second tag.
greeting_two += " World"
print(f"greeting_two is: {greeting_two}")
print(f"greeting_one is: {greeting_one}")
Timothy expected both variables to show "Hello World".
greeting_two is: Hello World
greeting_one is: Hello
He ran the code again with the same result.
“But you said they were references! You showed me this with a list!”
Margaret explained that strings behave differently from mutable containers.
Understanding String Immutability
Margaret used a marble bust as a metaphor:
- Stone (immutable) – a string cannot be altered in place, just like a stone statue.
- Whiteboard (mutable) – a list can be changed without creating a new object.
She illustrated the process:
- Python sees the original stone block labeled
"Hello". - The operation
greeting_two += " World"cannot carve" World"onto the existing stone. - Python creates a new stone block containing
"Hello World"in a new memory location. greeting_twois re‑bound to this new block, whilegreeting_oneremains attached to the original"Hello"block.
Thus, the two tags no longer reference the same object after the += operation.
Inspecting Object IDs
Timothy wanted concrete proof that a new object was created.
s = "Hello"
print(f"Start ID: {id(s)}")
s += " World"
print(f"End ID: {id(s)}")
Typical output:
Start ID: 2667049832100
End ID: 2667051284300
The differing IDs confirm that a new string object was allocated.
Immutable vs Mutable Types
| Category | Examples | Characteristics |
|---|---|---|
| Immutable (Stone) | str, int, float, tuple | Cannot be changed in place. Operations like +=, upper(), slicing create new objects (rebinding). Safe to share references. |
| Mutable (Whiteboard) | list, dict, set | Can be modified in place. Operations alter the original object, so shared references see the changes. |
Takeaway
- Strings (and other immutable types) are never altered; any “modification” results in a new object.
- Lists and other mutable containers can be changed in place, so aliases see the same updates.
- Understanding which objects are immutable versus mutable helps avoid unexpected bugs when sharing references.
Next time, Margaret and Timothy will explore “The Secret Life of Truth” — discovering that in Python, even emptiness can be False.