Sobes.tech
Junior — Middle

How can you perform deep copying of an object, creating a separate copy of its data?

sobes.tech AI

Answer from AI

For deep copying an object in Python, you can use the copy module and the deepcopy function, which creates a new copy of the object and recursively copies all nested objects so that changes in the copy do not affect the original.

Example:

import copy

original = {'a': [1, 2, 3], 'b': {'c': 4}}
copy_obj = copy.deepcopy(original)

copy_obj['a'].append(4)

print(original)  # {'a': [1, 2, 3], 'b': {'c': 4}}
print(copy_obj)  # {'a': [1, 2, 3, 4], 'b': {'c': 4}}