Copy
The copy
module provides tools for creating shallow and deep copies of objects, allowing for efficient object duplication and manipulation without affecting the original object.
# A shallow copy (both lists reference the same object)
list1 = [1, 2, 3]
list2 = list1
list2.append(4)
print(list1)
# A shallow copy created using slicing (creates a new list but does not copy nested objects)
list3 = [1, 2, 3]
list4 = list3[:]
list4.append(4)
print(list3)
# The same as the example above but using the copy module
import copy
list5 = [1, 2, 3]
list6 = copy.copy(list5)
list6.append(4)
print(list5)
# A deep copy (creates a completely independent copy, including nested objects)
list7 = [[1, 2], [3, 4]]
list8 = copy.deepcopy(list7)
list8[0].append(5)
print(list7)
In terms of classes, a shallow copy (copy.copy()
) creates a new instance that shares references to nested objects (attributes), whereas a deep copy (copy.deepcopy()
) creates a fully independent clone, including all nested objects.