InterviewHubPRO
Section Overview
Q20

Question 20 of 65

Part 2: Python Core Language, Internals & Runtime (6 - 25)

31%
Python & FastAPI•Part 2: Python Core Language, Internals & Runtime (6 - 25)

Shallow Copy (`copy.copy()`) vs Deep Copy (`copy.deepcopy()`);

In Simple Words:

  • Shallow Copy: Duplicates the outer container, but inserts references to the original nested objects.
  • Deep Copy: Recursively duplicates the container and all nested objects completely.
python
import copy

original = [[1, 2, 3], [4, 5, 6]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)

original[0][0] = 99
print(shallow[0][0]) # 99 (modified because nested list is shared!)
print(deep[0][0])    # 1 (safe and independent)