What is Deep Copy? What is Shallow Copy?
Deep Copy and Shallow Copy are two distinct methods used in programming to copy data structures, differing in their behavior when copying complex objects such as objects containing other objects or arrays.
Shallow Copy
Shallow Copy only copies the top-level structure of an object. If the object contains references to other objects, Shallow Copy does not copy the referenced objects themselves but copies the references. Consequently, the original object and the shallow-copied object share the same reference-type data.
Example:
Suppose we have an object A that contains a reference to another object B. If we shallow-copy A to get A', then A' will contain a reference to B, not a copy of B. If we modify B, this change will be reflected through the references in A and `A'.
pythonimport copy original_list = [1, 2, [3, 4]] shallow_copied_list = copy.copy(original_list) # Modify the nested list element in the original list original_list[2][0] = "changed" # Output the shallow-copied list print(shallow_copied_list) # Output will be [1, 2, ["changed", 4]]
In this example, modifying the nested list element in the original list also affects the shallow-copied list because they share the same reference to the nested list object.
Deep Copy
Deep Copy not only copies the top-level structure of an object but also recursively copies all members, including objects referenced within the object. Thus, the original object and the deep-copied object do not share any reference-type data.
Example:
Using the same objects A and B, if we deep-copy A to get A'', then A'' will contain a complete copy B' of B. At this point, if we modify B, A'''s B' is unaffected because B' is an independent object.
pythonimport copy original_list = [1, 2, [3, 4]] deep_copied_list = copy.deepcopy(original_list) # Modify the nested list element in the original list original_list[2][0] = "changed" # Output the deep-copied list print(deep_copied_list) # Output will be [1, 2, [3, 4]]
In this example, the deep-copied list retains its original structure and is unaffected by modifications to the nested list elements in the original list.
In summary, Shallow Copy only copies the top-level object, while Deep Copy copies all levels of the object, ensuring complete independence between the copied instance and the original data structure. In practical applications, the choice between Shallow Copy and Deep Copy depends on specific requirements and scenarios.