1 min read

Python Copy Module (Shallow vs Deep Copy)

Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other.

Importing the Module

import copy

Shallow Copy

A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

import copy

old_list = <a href='/1%2C%202%2C%203%5D%2C%20%5B4%2C%205%2C%206%5D%2C%20%5B7%2C%208%2C%209'>1, 2, 3], [4, 5, 6], [7, 8, 9</a>
new_list = copy.copy(old_list)

# Modify the new list
new_list[0][0] = 'a'

print("Old list:", old_list)
print("New list:", new_list)
# Output:
# Old list: <a href='/%27a%27%2C%202%2C%203%5D%2C%20%5B4%2C%205%2C%206%5D%2C%20%5B7%2C%208%2C%209'>'a', 2, 3], [4, 5, 6], [7, 8, 9</a>
# New list: <a href='/%27a%27%2C%202%2C%203%5D%2C%20%5B4%2C%205%2C%206%5D%2C%20%5B7%2C%208%2C%209'>'a', 2, 3], [4, 5, 6], [7, 8, 9</a>

Deep Copy

A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

import copy

old_list = <a href='/1%2C%202%2C%203%5D%2C%20%5B4%2C%205%2C%206%5D%2C%20%5B7%2C%208%2C%209'>1, 2, 3], [4, 5, 6], [7, 8, 9</a>
new_list = copy.deepcopy(old_list)

# Modify the new list
new_list[0][0] = 'a'

print("Old list:", old_list)
print("New list:", new_list)
# Output:
# Old list: <a href='/1%2C%202%2C%203%5D%2C%20%5B4%2C%205%2C%206%5D%2C%20%5B7%2C%208%2C%209'>1, 2, 3], [4, 5, 6], [7, 8, 9</a>
# New list: <a href='/%27a%27%2C%202%2C%203%5D%2C%20%5B4%2C%205%2C%206%5D%2C%20%5B7%2C%208%2C%209'>'a', 2, 3], [4, 5, 6], [7, 8, 9</a>

programming/python/python