Understanding Python Object Assignment, Mutable vs. Immutable Types, and Shallow vs. Deep Copying
This article provides a comprehensive guide to Python's memory management and object assignment mechanisms, clearly explaining the differences between mutable and immutable objects, direct assignment, shallow copying, and deep copying through practical code examples and visual diagrams.
This article provides a comprehensive guide to Python's object assignment, mutable versus immutable types, and the critical differences between shallow and deep copying.
Object Creation and Assignment: When assigning a value like a = "python" , Python creates the object in memory and points the variable to its address. Immutable objects (numbers, strings, tuples, frozensets) cannot be modified in place; any change allocates a new memory block. Mutable objects (lists, sets, dicts, custom classes) allow in-place modifications without changing the base address.
Direct Assignment: Assigning b = a simply points b to the same memory address as a . Modifying either variable affects the shared object.
Deep Copy: Using copy.deepcopy() creates a completely independent object with a new memory address. Changes to the original do not affect the copy, though it consumes more memory.
Shallow Copy: Using copy.copy() creates a new top-level object, but nested mutable elements still share the original memory addresses. Modifying first-level immutable elements is isolated, but altering nested mutable objects affects both.
Code Demonstrations:
import copy
a = [1, 2, 3]
print("-----Assignment-----")
b = a
print(a)
print(b)
print(id(a))
print(id(b))
print("-----Deep Copy-----")
c = copy.deepcopy(a)
print(a)
print(c)
print(id(a))
print(id(c))
print("-----Shallow Copy-----")
d = copy.copy(a)
print(a)
print(d)
print(id(a))
print(id(d))Special Case for Immutable Objects: Immutable types do not truly support copying. Both shallow and deep copies of immutable objects simply reference the original memory address.
Practical Applications: Use deep copying when a function must process data without altering the original input, or when passing objects to external methods to prevent side effects. Be cautious with shallow copying, as it only isolates the first layer and may cause unintended shared references in nested structures.
Byte Quality Assurance Team
World-leading audio and video quality assurance team, safeguarding the AV experience of hundreds of millions of users.
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.