Deep Copy vs. Shallow: Definitions
What is the difference between copy and deepcopy?
Answer
copy.copy()(shallow copy)
A shallow copy creates a new outer object and copies the references of the nested objects.import copy lst = [[1, 2], [3, 4]] shallow = copy.copy(lst) shallow[0][0] = 999 print(lst) # [[999, 2], [3, 4]]copy.deepcopy()(deep copy)
A deep copy creates a new outer object AND new copies of all nested objects, creating new references (new memory addresses) for each.import copy lst = [[1, 2], [3, 4]] deep = copy.deepcopy(lst) deep[0][0] = 999 print(lst) # [[1, 2], [3, 4]]