Shallow copy vs Deep copy is an important concept in every programming language. So here we see python how it will handle.
In Python, when you assign an object to a variable or pass it as an argument to a function, the object’s reference is copied, not the object itself. This means that the original object and the copy share the same memory location. This can lead to unexpected behaviour when working with mutable objects like lists and dictionaries. To avoid this, we can create a copy of the object using either shallow copy or deep copy.
Shallow Copy:
- A shallow copy creates a new object with a new memory location but keeps the references to the original object’s elements.
- If the original object is mutable, changes to its elements will affect both the original and the copied object.
- Shallow copy can be done using the slice operator [:], copy() method, and the built-in list(), dict(), and set() functions.
Here is an example of shallow copy:
original_list = [1, 2, [3, 4]] shallow_copy_list = original_list.copy() original_list[2][0] = 5 print(original_list) # Output: [1, 2, [5, 4]] print(shallow_copy_list) # Output: [1, 2, [5, 4]]
In this example, we create a shallow copy of the original_list
. When we modify the nested list inside the original_list
, the change is reflected in the shallow copy as well.
Deep Copy:
- A deep copy creates a new object with a new memory location and new references to the original object’s elements.
- If the original object is mutable, changes to its elements will not affect the copied object.
- Deep copy can be done using the deepcopy() method from the copy module.
Here is an example of deep copy:
import copy original_list = [1, 2, [3, 4]] deep_copy_list = copy.deepcopy(original_list) original_list[2][0] = 5 print(original_list) # Output: [1, 2, [5, 4]] print(deep_copy_list) # Output: [1, 2, [3, 4]]
In this example, we create a deep copy of the original_list
. When we modify the nested list inside the original_list
, the change is not reflected in the deep copy.