Difference between Deep Copy and Shallow Copy in Python

Difference between Deep Copy and Shallow Copy in Python

6 mins read790 Views Comment
Updated on Jun 8, 2023 11:51 IST

In this article you will find the difference between deep copy and shallow copy in python with programming examples. It also includes advantages and disadvantages.

2023_06_Feature-Image-Templates-13.jpg

A shallow copy and a deep copy are two different ways to create a new copy of an existing object. In the context of a class, a shallow copy creates a new instance of the class that references the same memory locations as the original object. In contrast, a deep copy creates a new class instance with its memory locations for all of the data within the original object. In this article, we will learn the Difference between Deep Copy and Shallow Copy in Python.

Table of Contents

Recommended online courses

Best-suited Python courses for you

Learn Python with these high-rated online courses

Free
6 weeks
– / –
2 weeks
– / –
16 weeks
1.7 K
3 months
– / –
– / –
4.24 K
2 weeks
3 K
3 weeks
– / –
4 months

Difference between Deep Copy and Shallow Copy in Python

Feature Shallow Copy Deep Copy
Copying Creates a new object with a new reference, but the content is the same reference as the original object. Creates a new object with a new reference, and the content is a new copy of the original object.
Relationship to Original Shares reference to original object, changes to copy affects the original. Independent from the original object, changes to copy do not affect the original.
Copying Behavior Only copies the top-level elements of an object. Copies all levels of nested objects.
Memory Efficiency Memory-efficient, as it doesn’t create new objects for nested references. Memory-intensive, as it creates new objects for nested references.
Performance Fast operation, as it doesn’t create new objects for nested references. Slow operation, as it creates new objects for nested references.

What is a Shallow Copy?

A shallow copy is used when you only need to make a duplicate version of an existing object so that changes made to one don’t affect the other. It copies only the top-level elements, not any child or nested objects. This type of copying can be useful if there are no references between different levels. Still, it can lead to unexpected behaviour if such references are present, as they will remain linked even after being copied into another variable. 

Shallow Copy Python

 
import copy
# Shallow copy example
original_list = [[1, 2, 3], [4, 5, 6]]
shallow_copy = copy.copy(original_list)
# Modify the first element of the shallow copy
shallow_copy[0][0] = 9
# Both the original and shallow copy will reflect the change
print("Original List:", original_list)
print("Shallow Copy:", shallow_copy)
Copy code

Output:

2023_06_3-2.jpg

Explanation:

In the output, you can see that modifying the first element of the shallow copy (shallow_copy[0][0] = 9) also affects the original list (original_list).

Note: You have to write copy. copy() for making the shallow copy.

Also read: Difference Between Methods and Functions in Python

Advantages of Shallow Copy

  1. Efficiency: Shallow copy is generally faster and less resource-intensive than a deep copy because it creates a new object with references to the existing data instead of copies of the entire data structure.
  2. Memory Savings: Shallow copy allows multiple objects to share the same underlying data. This can be advantageous when dealing with large data structures, as it reduces memory consumption since the duplicate objects only need to store references rather than duplicate the entire data.
  3. Simplicity: Shallow copy is simpler to implement and understand than deep copy. It typically involves directly copying the values of the object’s fields or properties to the new object.

Disadvantages of Shallow Copy

  1. Shared References: The main disadvantage of shallow copy is that if the original object or its references change, the changes will be reflected in all the shallow copies. This can lead to unexpected behaviour if you expect each copy to be independent.
  2. Data Integrity: Shallow copy may lead to data integrity issues if the shared data is modified accidentally or intentionally by one of the objects. It can be challenging to keep track of which objects have access to the shared data and ensure that changes are properly coordinated.
  3. Nested Objects: Shallow copy might not create independent copies of nested objects within the original object. Instead, it copies references to these nested objects, resulting in shared data. If changes are made to the nested objects, those changes will be reflected in all the shallow copies.

Explore: Python Online Courses & Certifications

Must check: Free Python Courses Online

What is Deep Copy?

Deep copies create exact replicas by recursively traversing through each element in an existing structure and creating separate instances for them inside a newly created structure which has no shared memory addresses with its source counterpart – making sure every piece remains independent from others during subsequent modifications on either side without affecting each other due to their lack interconnectivity links between them both at runtime as well post compilation level too! In short, this process ensures complete isolation, among various entities involved ensuring no unintended consequences arise due to their mutual interference upon execution time frame.

Python Deepcopy 

 
import copy
# Deepcopy example
original_list = [[1, 2, 3], [4, 5, 6]]
deep_copy = copy.deepcopy(original_list)
# Modify the first element of the deep copy
deep_copy[0][0] = 9
# Only the deep copy will reflect the change
print("Original List:", original_list)
print("Deep Copy:", deep_copy)
Copy code

Output: 

2023_06_4-1.jpg

Explanation:

In the output, you can observe that modifying the first element of the deep copy (deep_copy[0][0] = 9) does not affect the original list (original_list). The deep copy remains independent of the original list, and the change is only reflected in the deep copy itself.

Note: You have to write copy.deepcopy() for making a deep copy.

Advantages of Deep Copy

  1. Data independence: Deep copy creates independent copies of objects and data, ensuring modifications to one copy do not affect others.
  2. Modifiability: Deep copy allows for freely modifying the copied objects without unintentionally affecting the original or other copies.
  3. Immutable snapshots: Deep copy can create immutable snapshots of objects, preserving their state at a specific point in time.

Disadvantages of Deep Copy

  1. Performance Overhead: Deep copy tends to be slower and more memory-intensive than a shallow copy because it involves creating new objects and duplicating all the data within the original object and its nested objects. This can impact the performance of your program, especially when dealing with large or complex data structures.
  2. Resource Consumption: Deep copy requires additional memory to store the copied data, potentially leading to higher memory consumption. It can strain system resources if your program frequently performs deep copies on large objects or in memory-constrained environments.
  3. Complexity: Deep copy can be more complex to implement and understand, especially when dealing with complex object graphs containing circular references or objects with complex internal structures. Managing references and ensuring proper duplication of all objects and data can be challenging.

Conclusion

Understanding how these two types work will help developers decide when best to use either technique depending on their needs for cloning objects within their applications codebase – thus leading towards more efficient & bug-free software development cycles overall! If you liked the article, then please do like and share it with your friends.

Related reads:

Introduction to Recursion Functions in Python
Introduction to Recursion Functions in Python
When programming, in many places you would have implemented a function that invokes or calls another function. However, when a function calls itself we call that recursion.
Find the Second Occurrence of a Substring in Python String
Find the Second Occurrence of a Substring in Python String
During Python programming, you will come across instances where you would need to find the second occurrence of a substring in Python a given string. For example, finding the second...read more
Python Sorted() Function
Python Sorted() Function
The sorted() function is designed to return a new sorted list from the items in an iterable. Whether you're dealing with numbers, strings, or custom objects, sorted() can handle it...read more

FAQs

How does deep copy work in Python?

Deep copy creates a new object and recursively copies all nested objects within the original object. It creates independent copies of the nested objects, ensuring that any modifications made to one copy do not affect the others.

How does shallow copy work in Python?

Shallow copy creates a new object and populates it with references to the original object's nested objects. It copies the references instead of creating independent copies of the nested objects. Any changes made to the original object or its nested objects will be reflected in the shallow copy.

What are the advantages of deep copy in Python?

Deep copy provides data independence, allowing each copy to have its own separate state. It also enables modifiability, as you can freely modify the copied objects without affecting the original or other copies. Deep copy can be used to create immutable snapshots of objects, preserving their state at a specific point in time.

What are the advantages of shallow copy in Python?

Shallow copy has advantages such as efficiency and memory savings. It is faster and less resource-intensive than deep copy since it doesn't create duplicate copies of the entire data structure. Shallow copy also allows for sharing the same underlying data among multiple objects, reducing memory consumption.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio