Python Shallow and Deep Copy
When creating copies of arrays or objects one can make a deep copy or a shallow copy . Shallow copying is creating a new object and then copying the non static fields from the current object to the new object. If the field is a value type , a bit by bit copy of the field is performed. If the field is a reference type , the reference is copied but the referred object is not, therefore the original object and its clone refer to the same object. While Deep copying is creating a new object and then copying the non-static fields of the current object to the new object. If a field is a value type, a bit by bit copy of the field is performed. If a field is a reference type, a new copy of the referred object is performed. exampleHere using normal assignment operating to copy (color4 = color3)
print (id(color3) == id(color4))output is True because color3 is the same object as color4
print (id(color3[0]) == id(color4[0]))output is True because color4[0] is the same object as color3[0]
In the next line we perform Shallow Copy
color4 = copy.copy(color3)A shallow copy constructs a new compound object and then inserts references into it to the objects found in the original.
print (id(color3) == id(color4))output is False because color4 is now a new object
print (id(color3[0]) == id(color4[0]))output is True because color4[0] is the same object as color3[0]
In the next line we perform Deep Copy
color4 = copy.deepcopy(color3)A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.
print (id(color3) == id(color4))output is False because color4 is now a new object
print (id(color3[0]) == id(color4[0]))output is False because color4[0] is now a new object
- Keywords in Python
- Python Operator - Types of Operators in Python
- Python Variables and Data Types
- Python Datatype conversion
- Python Mathematical Function
- Basic String Operations in Python
- Python Substring examples
- How to check if Python string contains another string
- Check if multiple strings exist in another string : Python
- Memory Management in Python
- Python Identity Operators
- What is a None value in Python?
- How to Install a Package in Python using PIP
- How to update/upgrade a package using pip?
- How to Uninstall a Package in Python using PIP
- How to call a system command from Python
- How to use f-string in Python
- Python Decorators (With Simple Examples)
- Python Timestamp Examples