The Secret Life of Python: The Dangerous Reflection
Source: Dev.to
Understanding Python aliasing, references, and the trap of shallow copies
Timothy needed to add tentative guests to a list without altering the original master_list. He thought assigning the list to a new variable would create a copy:
# Timothy's "Safety" Plan
master_list = ["Alice", "Bob", "Carol"]
draft_list = master_list
Note: All the methods above produce a shallow copy. For a list of immutable items (e.g., strings, numbers) this is sufficient. If the list contains mutable objects (e.g., other lists, dictionaries), the inner objects are still shared. In such cases a deep copy (
copy.deepcopy) is required.
Takeaway
- Assignment (
b = a) creates an alias, not a copy. - Use slicing,
.copy(), or thelist()constructor for a shallow copy. - Be aware of the shallow‑copy limitation when dealing with nested mutable structures.
“A name is not the thing itself. And a map is not the territory.” – Margaret
Next episode: “The Matryoshka Trap” – exploring deep copies and nested mutable objects.