Sobes.tech
Junior — Middle

Have you encountered creating deep copies of objects when using Python?

sobes.tech AI

Answer from AI

In Python, the copy module and the deepcopy() function are used to create a deep copy of an object. A deep copy creates a new object and recursively copies all nested objects, unlike a shallow copy, which only copies the top level.

Example:

import copy

original = [[1, 2], [3, 4]]
shallow_copy = copy.copy(original)
deep_copy = copy.deepcopy(original)

original[0][0] = 99

print(shallow_copy)  # [[99, 2], [3, 4]] — changed, because it is a shallow copy
print(deep_copy)     # [[1, 2], [3, 4]] — unchanged, because it is a deep copy

Deep copies are useful when you want to avoid side effects when modifying nested data structures.