Shallow and Deep
Shallow and Deep
operations.
import copy
copy.copy(k)
copy.deepcopy(k)
k represents the original list.
Shallow Copy
A shallow copy creates a new object which stores the reference of
the original elements.
So, a shallow copy doesn't create a copy of nested objects, instead it
just copies the reference of nested objects. This means, a copy
process does not recurse or create copies of nested objects itself.
Adding new nested object using Shallow copy
import copy
old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
new_list = copy.copy(old_list)
old_list[1][1] = 'A'
print("Old list:", old_list)
print("New list:", new_list)
output:
Old list: [[1, 1, 1], [2, 'A', 2], [3, 3, 3]]
New list: [[1, 1, 1], [2, 'A', 2], [3, 3, 3]]
Deep Copy
A deep copy creates a new object and recursively adds the copies of
nested objects present in the original elements. The deep copy
creates independent copy of original object and all its nested objects.
Adding a new nested object in the list using Deep copy
import copy
old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
new_list = copy.deepcopy(old_list)
old_list[1][0] = 'B'
print("Old list:", old_list)
print("New list:", new_list)
output:
Old list: [[1, 1, 1], ['B', 2, 2], [3, 3, 3]]
New list: [[1, 1, 1], [2, 2, 2], [3, 3, 3]]