What Is the Difference Between `deepcopy` and `shallowcopy` in Python?

·

`deepcopy` creates a new object and recursively copies all objects found in the original. `shallowcopy` creates a new object but inserts references into it to the objects found in the original.

Example:

import copy

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

shallow[0][0] = 100
print(original)  # [[100, 2, 3], [4, 5, 6]]
print(deep)      # [[1, 2, 3], [4, 5, 6]]

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *