What is the difference between shallow copy and deep copy in Python?

A shallow copy creates a new outer object but the inner objects are still shared with the original. A deep copy creates a new outer object and also new copies of everything inside it.

import copy

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

original[0].append(99)

print(shallow)
print(deep)

Output:

Tutorials Class - Output Window

[[1, 2, 99], [3]]
[[1, 2], [3]]

The shallow copy changed too, because its inner list is the same object as in the original. The deep copy stayed safe. Note that b = a does not copy at all, it only gives a second name to the same object. Use a deep copy when the data has lists or dictionaries inside other lists or dictionaries.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.