What is difference between shallow copy and deep copy in Python?

A shallow copy creates a new object but references the original data, while a deep copy creates a completely independent copy of the object and its nested data.

Suppose you have a recipe book with multiple pages, each containing a list of ingredients. A shallow copy of the book is like making a photocopy of the pages—if you modify the ingredients on one page, it will also change in the original book. In contrast, a deep copy is like creating an entirely new recipe book with separate pages, where you can modify the ingredients in the copy without affecting the original.

In Python, copying objects is common when replicating or duplicating data structures like lists, dictionaries, or custom objects. However, not all copying methods are the same.

There are two types of object copying:

  1. Shallow copy

  2. Deep copy

Shallow copy and deep copy
Shallow copy and deep copy

Understanding the difference between these two helps avoid unintended behavior in our code. Let's move forward to understand this concept in depth:

Deep copy definition

A deep copy duplicates an object along with all objects it references, creating a completely independent copy. Any modifications made to the deep-copied object won’t affect the original object, making it ideal when working with complex, nested data structures like lists within lists or dictionaries containing other dictionaries.

Syntax of Python deep copy

The copy module provides the deepcopy() function, which can be used to create deep copies of objects.

Syntax:

import copy
# Example of deep copy
original = [[1, 2], [3, 4]]
deep_copied = copy.deepcopy(original)

In this example, deep_copied is a fully independent duplicate of the original object, and changes to one will not affect the other.

Example of Python deep copy

Here’s a coding example that demonstrates deep copy in Python:

import copy
# Original list with nested lists
original_list = [[1, 2], [3, 4]]
# Creating a deep copy of the original list
deep_copy = copy.deepcopy(original_list)
# Modifying the nested list in the deep copy
deep_copy[0][1] = 99
# Output the original and deep copy lists
print("Original List:", original_list)
print("Deep Copy:", deep_copy)

In this case, modifying the deep copy does not affect the original list, because the deep copy creates independent copies of the nested objects.

Try modifying the nested elements to see how they behave independently. For example, change deep_copy[0][1] = 99 and observe how the original list remains unaffected, while the deep copy reflects the change.

Definition of shallow copy

A shallow copy creates a new object, but it only copies the references to the objects nested within it. In other words, a shallow copy duplicates the top-level structure, but the nested elements (such as lists inside a list) still reference the original objects. Modifications to these nested objects will affect both the original and the copied object.

Syntax of Python shallow copy

The copy module also provides the copy() function for creating shallow copies.

Syntax:

import copy
# Example of shallow copy
original = [[1, 2], [3, 4]]
shallow_copied = copy.copy(original)

In this case, shallow_copied is a new object, but the inner lists still reference the original ones, meaning changes to the inner lists affect both copies.

Example of Python shallow copy

Here’s a coding example that demonstrates both shallow copy in Python:

import copy
# Original list with nested lists
original_list = [[1, 2], [3, 4]]
# Creating a shallow copy of the original list
shallow_copy = copy.copy(original_list)
# Modifying the nested list in the shallow copy
shallow_copy[0][1] = 99
# Output the original and shallow copy lists
print("Original List:", original_list)
print("Shallow Copy:", shallow_copy)

In this example, modifying the shallow copy affects the original list because the nested lists are still referencing the same objects.

Difference between shallow and deep copy

We have listed some key differences between shallow and deep copy below:

shallow copy vs. deep copy​

Aspect

Shallow Copy

Deep Copy

Copies nested objects

No, nested objects reference the original ones

Yes, nested objects are also duplicated

Independent from original?

Only at the top level

Completely independent from the original

Impact on original object

Changes to nested data affect the original object

No effect on the original object, including nested data

Function used

copy.copy()

copy.deepcopy()

Use case

When we need a quick copy of an object, but can share references to nested data

When we need a full, independent duplicate, including all nested data

Key takeaways:

  • Shallow copy: Creates a new object but references the same nested data from the original object. Changes to nested elements affect both objects.

    • Function: copy.copy()

    • Use case: When sharing references is acceptable.

  • Deep copy: Creates a completely independent copy, including all nested data. Changes do not affect the original object.

    • Function: copy.deepcopy()

    • Use case: For fully independent duplicates.

  • Impact: Deep copy is suitable for complex data structures; shallow copy is faster but retains references to nested data.

Exercise

  1. Create a dictionary with nested lists, such as {'fruits': ['apple', 'banana'], 'vegetables': ['carrot', 'lettuce']}.

  2. Make a shallow copy using copy() and a deep copy using copy.deepcopy().

  3. Modify an item in one of the nested lists in each copy and print all versions to observe the differences.

import copy
# Original dictionary with nested lists
# Create a shallow copy
# Create a deep copy
# Modify an item in the nested lists of shallow and deep copies
# Output to see the differences

If you’re stuck, refer to the solution below for guidance.

Ready to deepen your Python knowledge? Start our Become a Python Developer path, beginning with Python's basic concepts and advancing to more complex topics, preparing you for a career as a Python developer.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


How can I start my career in Python?

Learning to code can be exciting, and interactive platforms are a great way to start. Educative’s Learn to Code path helps beginners become job-ready through gamified, project-based lessons, making concepts easier to understand and apply. Their step-by-step courses ensure both practical skills and knowledge for real-world success.


Is slicing in Python a shallow copy?

Yes, slicing in Python creates a shallow copy of the sliced portion, meaning changes to the nested objects will affect both the original and the sliced copy.


Is copy() a deep copy in Python?

No, Python’s copy.copy() creates a shallow copy, duplicating the top-level object but still referencing the original nested objects.


How do you perform deep and shallow copies using the copy module in Python?

To create a shallow copy, use copy.copy(), and for a deep copy, use copy.deepcopy() from the copy module. Shallow copies duplicate the top-level structure, while deep copies duplicate all nested objects as well.


What happens when copying mutable objects in Python?

When copying mutable objects (like lists or dictionaries), shallow copies share references to the original object’s nested elements, meaning changes to the nested data affect both the original and copy. Deep copies, however, create completely independent objects, including all nested elements.


Is slicing a list a shallow copy?

Yes, slicing a list in Python creates a shallow copy. It copies the top-level elements of the list, but the elements themselves (if they are mutable objects) are still referenced, meaning changes to nested elements will affect both the original and the sliced list.


Free Resources

Copyright ©2024 Educative, Inc. All rights reserved