Understanding Python Assignment, Shallow Copy, and Deep Copy
This article explains how Python handles object assignment, the differences between shallow and deep copying using the copy module, and special cases such as immutable types and tuples, providing clear examples and visual output to avoid common pitfalls.
Understanding Python Assignment, Shallow Copy, and Deep Copy
In Python, assigning an object creates a reference to the same memory address, which can lead to unexpected behavior if not understood.
1. Object Assignment
The following code demonstrates simple assignment:
The output shows that both will and wilber refer to the same list object, so changes to one affect the other. Immutable types like str create a new object when modified.
2. Shallow Copy
Using copy.copy() creates a new container object but retains references to the original elements:
The result shows that the new list wilber is a different object from will, yet its mutable elements still reference the same objects, so modifications to those elements are reflected in both lists.
3. Deep Copy
Using copy.deepcopy() creates a completely independent copy of the container and all nested objects:
The output confirms that wilber is a distinct object and its elements are also new objects, so changes to will do not affect wilber.
4. Special Cases
Non‑container types such as numbers, strings, and other atomic objects are not copied; the identity check obj is copy.copy(obj) or obj is copy.deepcopy(obj) returns True. For tuples containing only atomic objects, deep copy is ineffective.
5. Summary
Python object assignment passes references (memory addresses).
Using copy.copy() performs a shallow copy: the container is new, but its elements remain references to the originals.
Using copy.deepcopy() creates a fully independent copy of the container and all nested objects.
Immutable or atomic types are not truly copied; they remain the same object.
If a tuple contains only atomic objects, deep copy has no effect.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
