Python shallow vs deep copy

whitehousechef·2023년 12월 6일

shallow

Shallow copy .copy() which was what I have been doing, copies the top level of the object. So if you have

import copy

original_list = [1, [2, 3], [4, 5]]
shallow_copy = original_list.copy()

shallow_copy[0] = 69
print(original_list)  # [1, [2, 3], [4, 5]]
print(shallow_copy)   # [69, [2, 3], [4, 5]]

this is fine cuz it copies the top level of the object. But for that inner list, it is not copied so if you do

import copy

original_list = [1, [2, 3], [4, 5]]
shallow_copy = original_list.copy()

shallow_copy[1][0] = 99
print(original_list)  # [1, [99, 3], [4, 5]]

modifying the inner object in the copied objec t will affect the original object too

deep

but deepcopy() copies outer as well as Inner objects so the original object will not be modified if we change the deepcopy's inner object like

import copy

original_list = [1, [2, 3], [4, 5]]
deep_copy = copy.deepcopy(original_list)

deep_copy[1][0] = 99
print(original_list)  # [1, [2, 3], [4, 5]]

0개의 댓글