Python tutorials > Data Structures > Lists > What is shallow vs deep copy?
What is shallow vs deep copy?
Shallow Copy: Basics
import copy
original_list = [1, 2, [3, 4]]
shallow_copy = copy.copy(original_list)
print(f"Original list: {original_list}")
print(f"Shallow copy: {shallow_copy}")
# Modifying the inner list in the shallow copy
shallow_copy[2][0] = 5
print(f"Original list after modification: {original_list}")
print(f"Shallow copy after modification: {shallow_copy}")
Deep Copy: Basics
import copy
original_list = [1, 2, [3, 4]]
deep_copy = copy.deepcopy(original_list)
print(f"Original list: {original_list}")
print(f"Deep copy: {deep_copy}")
# Modifying the inner list in the deep copy
deep_copy[2][0] = 5
print(f"Original list after modification: {original_list}")
print(f"Deep copy after modification: {deep_copy")
Concepts Behind the Snippet
A shallow copy creates a new object (e.g., a new list), but the elements within the new object are references to the original object's elements. Changes to these inner elements will affect both the original and the shallow copy.
Deep Copy:
A deep copy creates a new object and recursively copies all objects found within the original object. This means that all elements within the new object are independent copies of the original object's elements. Changes to these inner elements will only affect the deep copy. It can be more resource-intensive than a shallow copy, as it requires creating new objects for all nested elements.
Real-Life Use Case
Best Practices
Interview Tip
When to Use Them
Use Deep Copy When:
Memory Footprint
Alternatives
For example, copying a simple list of numbers can be done efficiently via slicing: `new_list = original_list[:]`.
Pros of Shallow Copy
Cons of Shallow Copy
Pros of Deep Copy
Cons of Deep Copy
FAQ
-
Why does modifying the shallow copy change the original list's inner list?
Because the shallow copy only creates references to the inner list objects in the original list. Both lists point to the same inner list in memory. -
When is a deep copy absolutely necessary?
When you have nested mutable objects and you need to modify the copy without affecting the original. Think of scenarios where you want to perform operations on data without any side effects on the original source. -
Is deep copy always slower than shallow copy?
Yes, deep copy is generally slower because it needs to recursively copy all nested objects, while a shallow copy only copies the top-level container.