Differences Between Shallow and Deep Copy
In Python, an object
is a fundamental unit that contains both data and the methods to handle that data.
In Python, nearly everything such as numbers, strings, and sets can be considered as objects.
There are two methods to copy an object: Shallow Copy
and Deep Copy
.
-
A shallow copy affects both the original and the copy when modified.
-
A deep copy creates a completely independent copy of the original, meaning changes to one do not affect the other.
Shallow Copy
A shallow copy
shares the internal objects between the copied object and the original object.
If you modify the copied object, the original object will also change.
You can perform a shallow copy
using the list()
function to create a new list.
The code example below demonstrates that changing an element in the copied object also changes the original object.
# Create original list
original = [1, 2, 3, [4, 5, 6]]
# Perform a shallow copy and assign to 'shallow_copied'
shallow_copied = list(original)
# Modify nested list element in 'shallow_copied'
shallow_copied[3][0] = 99
# The original list is also changed
print("Original:", original)
# [1, 2, 3, [99, 5, 6]]
In the above example, changing the nested list [4, 5, 6]
in the shallow_copied
list also changes the original original
list.
Deep Copy
A deep copy
creates new objects at every level of the hierarchy.
The copied object is completely independent of the original object, so modifying the original object does not affect the copied object.
The code example below demonstrates that modifying an element in the copied object does not affect the original object.
# Import the 'copy' module
import copy
original = [1, 2, 3, [4, 5, 6]]
deep_copied = copy.deepcopy(original)
deep_copied[3][0] = 99
# Print results
print("Original:", original)
# Outputs [1, 2, 3, [4, 5, 6]] : the original list is unchanged
print("Deep Copied:", deep_copied)
# Outputs [1, 2, 3, [99, 5, 6]] : only the copied list is changed
In the code above, the import
keyword helps to bring in external code so it can be used.
The copy
module is built into Python and allows you to perform a deep copy using the copy.deepcopy()
function.
Note: In programming, a
Module
is an external code file that is composed of functions, variables, classes, etc.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.