Python theorytheory 0/50 · 0%
Foundations · hard

43. Memory model: mutability, references, and copy

Shared references, shallow vs deep copy.

Assignment binds names to the same object; mutable objects can be changed through any reference that points to them, which surprises newcomers.

python
a = [1, 2, 3]
b = a
b.append(4)
print(a)   # [1, 2, 3, 4] -- same list!

import copy
c = a.copy()          # shallow copy, new outer list
d = copy.deepcopy(a)  # recursively copies nested structures too

A shallow copy duplicates the top-level container but still shares references to nested mutable objects; `copy.deepcopy` recursively copies everything, which matters when lists contain other lists or dicts that must be fully independent.

Check your understanding

  1. 1. After `b = a; b.append(4)` where a is a list, what happens to `a`?

  2. 2. What does a shallow copy NOT do?

  3. 3. When would you need `copy.deepcopy` instead of `.copy()`?