Data Types - General - Advanced Concepts Flashcards

1
Q

When making copies of mutable objects, it’s important to use “safe” methods of copying.

What’s the difference between a “shallow” vs “deep” copy?

A

A shallow copy does not copy any “Nested” structure. It only copies the “outer shell”. E.g.,

a = [[1, 2], [3, 4]]
b = a.copy() # shallow copy
b[0][0] = 99

print(a) # [[99, 2], [3, 4]]
print(b) # [[99, 2], [3, 4]]

You can see that changing the “Nested Structure” of b has also changed a.

To make a “deep copy” use, “b = copy.deepcopy(a)”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly