![]() |
VOOZH | about |
In Python, Dictionary like other non-primitive data structures can be copied using various methods. The key distinction lies in the depth of the copy. In this article, we are going to learn about deep copy and shallow copy in Python.
In Python, a shallow copy creates a new object that references the same underlying data of the original object. This means although the objects have different names, both objects point to the same memory location. So if you make changes in either of the objects then the changes will affect both objects.
The code you've provided does indeed demonstrate Shallow copy in Python dictionaries.
{'a': 1, 'b': [1, 2, 3]}
{'a': 1, 'b': [1, 2, 3]}
{'a': 1, 'b': [1, 4, 3]}
{'a': 1, 'b': [1, 4, 3]}
Or You can Also make a shallow Copy of Dictionary by copy method by importing copy module
shallow_copy = original_dict.copy()In Python, a Deep copy creates a completely new object. The objects have different names but here both object will not point to the same memory location. So if you make changes in either of the objects then the changes will not affect both the objects.
The code you've provided does indeed demonstrate deep copy in Python dictionaries.
{'a': 1, 'b': [1, 2, 3]}
{'a': 1, 'b': [1, 2, 3]}
{'a': 1, 'b': [1, 2, 3]}
{'a': 1, 'b': [1, 4, 3]}
Feature | Shallow Copy | Deep Copy |
|---|---|---|
Definition | Shallow copy creates a new object, but it references the same objects in the original structure. | Deep copy creates a new object and recursively copies all objects found in the original. |
Memory Usage | Consumes less memory as it shares reference to the objects. | Consumes high memory as compared to shallow copy. |
Copied Objects | Changes made in nested object will reflect in both original and copied structure. | Changes made in nested object will not reflect in both original and copied structure. |
Performance | Faster to create as it does not involve in copying nested object. | Slower to create due to recursive copying of all objects |
Dependency | Dependent on structure. changes in nested objects affect both the original and the copy. | Independent on structure. changes in nested objects only affect the copy, not the original. |
Related Article:Copy in Python: Deep Copy and Shallow Copy