Deep Copy and Shallow Copy in Python

Deep-Copy-and-Shallow-Copy-in-Python-feature.jpg

While working with Python, you often have to deal with objects like lists, dictionaries, and sets. Sometimes, you might need to make a duplicate copy of these objects. But not all copies behave in the same manner. This is where you can use Deep Copy and Shallow Copy in Python. It is important to understand the difference so that you can avoid the unexpected behavior in your programs. In this blog, we will discuss everything about Python Deep copy, Python shallow copy, and how they work in real-life scenarios.

Table of Contents

What is Python Deep Copy?

A Deep Copy in Python is used to create a brand new object and fills it with copies of all the items from the original object. This includes the nested objects, one by one. This means that it goes through each item inside the original object and makes a copy of that object. As a result, any changes made in the copied object will not do any harm to the original object.

Syntax of Python Deep Copy

The syntax of deep copy in Python is shown below:

copy.deepcopy()
Unlock Python: Power Up Your Programming Skills!
Dive into real-world coding projects and become confident in writing clean, efficient Python code.
quiz-icon

What is Python Shallow Copy?

A Python Shallow Copy is used to make a new object, but it does not create copies of the items inside it. Instead of that, it keeps references to the original items. This means that only the outer structure is copied, while the nested objects are shared. Due to this, if you change a nested item in the copied object, the same change will be reflected in the original object.

Syntax of Python Shallow Copy

The syntax of shallow copy in Python is shown below:

copy.copy()

How to Create Deep Copy and Shallow Copy in Python?

While working on lists, dictionaries, or other objects in Python, you might want to make a copy of them. However, copying objects is not a simple thing to do. This is because some objects contain other objects inside them (also called nested objects). In such cases, Python provides you with two ways to copy objects: Shallow Copy and Deep Copy. The example codes for Shallow Copy and Deep Copy are given below:

1. Creating a Shallow Copy in Python

A Python Shallow Copy is used to create a new object, but it keeps the references to the inner objects of the original object. This means that changes that are made to the nested objects in the copied object will also appear in the original object. For creating a shallow copy, you can use the copy module in Python.

Example:

Python

Output:

Creating Shallow Copy in Python

Explanation: In the above Python program, changing the inner list in the shallow copy also affects the original list. This happens because both lists share references with the same nested objects.

2. Creating a Deep Copy in Python

A Python Deep Copy is used to create a completely new object and then copies all the items from the original object, including any nested objects. This means that both the outer and inner objects are duplicated, and changes made in one do not affect the other. For creating a deep copy in Python, you can use the copy.deepcopy() function.

Example:

Python

Output:

Creating Deep Copy in Python

Explanation: In the above Python program, the deep copy does not affect the original list. This is because both the outer and inner objects are completely separate.

Copying Simple Data Structures in Python

In this section, we are going to discuss various ways to copy different types of data structures using both Shallow Copy and Deep Copy.

1. Copying a List

Lists in Python are one of the most common data structures. It is very easy to create a shallow copy or a deep copy of a list using the copy module.

Example: Shallow Copy of a List

Python

Output:

Shallow copying a List

Explanation: In the above Python code, changing the nested list inside the Python Shallow Copy also affects the original list. This is because both lists have the same inner elements.

Example: Deep Copy of a List

Python

Output:

Deep Copying a List

Explanation: In this case, the Python Deep Copy is used to create a completely independent copy. Therefore, changes made in one list do not affect the other.

Get 100% Hike!

Master Most in Demand Skills Now!

2. Copying a Dictionary

You can also apply deep copy and shallow copy in Python to dictionaries. The code examples are given below for your reference:

Example: Shallow Copy of a Dictionary

Python

Output:

Shallow Copying a Dictionary

Explanation: In the above example, as the nested lists are still linked, the changes that are made in the Python Shallow Copy reflect in the dictionary.

Example: Deep Copy of a Dictionary

Python

Output:

Deep Copying a Dictionary

Explanation: Here, the Python Deep Copy creates a duplicate copy of all the inner elements. Therefore, the original dictionary remains unchanged.

3. Copying a Set

In Python, you can copy sets as well, although they do not usually contain nested objects that are mutable. Still, you can use both shallow copy and deep copy.

Example:

Python

Output:

Copying a Set

Explanation: The above code is used to create a shallow copy and a deep copy of a set in Python. Since the set doesn’t have nested objects, both copies are the same as the original.

Copying Objects of User-Defined Classes

While working with objects of user-defined classes, it is a slightly different process copying them than copying the built-in data structures like lists or dictionaries. Python provides you with mechanisms to create shallow copies and deep copies of class objects, which helps you to avoid any unwanted changes in your original objects. In this section, we will explore them step-by-step:

1. Default Copy Behavior in Python

By default, when you assign one object to another, Python does not create a new object. Both variables point to the same memory location.

Example:

Python

Output:

Default Copy Behavior in Python

Explanation: In the above code, both original_student and assigned_student are used to point to the same object. If you change one of them, it will affect the other. That is why Python Shallow Copy and Python Deep Copy are important for creating independent copies.

2. Using copy.deepcopy() in Python

When you need a completely independent copy of a class object that includes all the nested attributes, you can use Python Deep Copy.

Code:

Python

Output:

Using copy.deepcopy() in Python

Explanation: By using copy.deepcopy(), you can create a completely independent object. Changes that are made in the copied object do not affect the original object. This can be useful for classes having nested and mutable attributes like lists, dictionaries, or other objects.

3. Defining __copy__ Method in Python

In order to get more control over how your class objects are copied, you can define it using the __copy__ method. This helps you customize Python Shallow Copy behavior for your user-defined class.

Code:

Python

Output:

Defining __copy__ Method in Python

Explanation: By defining __copy__, you can control the way Python Shallow Copy behaves. In this case, the list called grades is copied. So, the modifications in the shallow copy do not have an impact on the original list. Without defining __copy__, the default shallow copy would just be a reference to the same nested objects. This works only for one level of nesting. For deeper nesting, use deepcopy().

Difference between Deep Copy and Shallow Copy in Python

Given below is the difference between Python Deep Copy and Python Shallow Copy in Python in tabular format:

Aspect Shallow Copy in Python Deep Copy in Python
Meaning Creates a new object but keeps references to the original nested objects. Creates a completely new object and also copies all nested objects inside it.
Copy Level Only copies the outer structure (top level). Copies both the outer structure and all nested objects (recursive copy).
Effect of Changes Changes made to nested objects in the copy also appear in the original. Changes made to any part of the copy do not affect the original.
Memory Usage Uses less memory since nested objects are shared. Uses more memory because everything is duplicated.
Speed Faster since it doesn’t duplicate nested data. Slower as it copies all nested objects.
Function Used copy.copy() copy.deepcopy()
Best Used When The object has simple, non-nested data. The object contains complex or nested structures like lists inside lists or dictionaries inside lists.

Common Mistakes in Deep Copy and Shallow Copy in Python

Given below are some of the common mistakes that occur in Deep Copy and Shallow Copy in Python:

1. There are many people who think that the Python Shallow Copy is used to make duplicate copies of everything in the object, but it only copies the outer layer. The nested objects are used to point to the same memory location. Therefore, any changes made to them also affect the original data.

2. While working with complex data like lists inside lists or dictionaries inside lists, using copy.copy() can result in unexpected behavior. You need to use copy.deepcopy() to make sure that every nested object is also copied independently.

3. Another common mistake that occurs is when copying mutable objects (like lists or dictionaries) with a shallow copy and then modifying them. This can unintentionally change both the copied and original objects. This is because they share the same nested references.

4. For immutable objects like integers, strings, or tuples, you don’t have to use Python Deep Copy or Python Shallow Copy. This is because they cannot be changed after they are created. Copying them would just waste your memory and time.

5. Sometimes beginners forget to import the copy module using copy.copy() or copy.deepcopy(). Without importing it, Python will show a NameError, which says that copy is not defined.

Best Practices for Deepcopy or Shallow Copy in Python

1. If your object does not have nested structures, you can use Python Shallow Copy with copy.copy(). It is much faster and uses less memory as it only copies the top-level elements.

2. When your data consists of lists, dictionaries, or objects inside other objects, you should use Python Deep Copy with copy.deepcopy(). This helps to ensure that changes made to the copy do not affect the original object.

3. You should not use shallow or deep copy for immutable objects like strings, numbers, or tuples, as they cannot be changed.

4. Deep Copy in Python can be slower and can consume a lot of memory. This is because it copies every element in a recursive way. You should only use it when it is truly required.

5. After you have created a copy, you should print or inspect both the original and the copied object to confirm that they behave independently.

Real-World Applications of Shallow and Deep Copies

1. You can use a deep copy to make a backup of data before making any changes. This helps to ensure that the original data remains safe even though the copied version is modified.

2. You can also use a shallow copy in game development. This helps to make a duplicate copy of the game objects (like players or enemies) that share the basic attributes but have unique values.

3. During the model training process, developers often use Deep Copy to make duplicate datasets or model parameters. This helps to avoid accidental overwrites of the original data.

4. In web applications, Shallow Copy can be used while copying data or UI elements, where you only need the structure, and not a full deep copy of every detail.

5. While you are testing multiple scenarios, a Deep copy can help you to create independent copies of the same data so that any changes that are made in one test do not affect the others.

Start Coding in Python for Free: No Experience Needed!
Begin writing actual Python code through interactive, beginner-friendly modules completely for free.
quiz-icon

Conclusion

It is important for you to understand the difference between Python Deep Copy and Python Shallow Copy when working with complex data structures. You can use a shallow copy when you need to make a top-level duplicate of data, while you can use a deep copy when you want a completely independent copy of your data. Knowing when to use deep copy and shallow copy helps you to avoid unexpected changes, save memory, and write cleaner, more efficient code in Python. By following the best practices and being careful of the common mistakes, you can have a good idea of the use of deep copy and shallow copy in Python in real-world scenarios.

Take your skills to the next level by enrolling in the Python Course today and gaining hands-on experience. Also, prepare for job interviews with Python Interview Questions prepared by industry experts.

Deep Copy and Shallow Copy in Python – FAQs

Q1. Can I use slicing instead of copying functions in Python?

Yes, you can use slicing to create a shallow copy of lists. But it does not work for all types of data, like dictionaries and sets.

Q2. What happens when I deep copy an object in Python?

If you deepcopy an object in Python, it creates a completely independent duplicate of that object, including all nested objects.

Q3. Does deepcopy work with custom classes automatically?

Yes, deepcopy can work with custom classes automatically. copy.deepcopy() works with most user-defined classes unless the class restricts copying using special methods.

Q4. Can I copy only specific elements instead of the whole object?

You can manually copy only the specific elements you need by creating a new object and assigning selected values.

Q5. Is deepcopy safe to use with circular references?

Yes, it is safe to use copy.deepcopy() as it can handle circular references safely. Therefore, it won’t create any infinite loops while copying.

About the Author

Software Developer | Technical Research Analyst Lead | Full Stack & Cloud Systems

Ayaan Alam is a skilled Software Developer and Technical Research Analyst Lead with 2 years of professional experience in Java, Python, and C++. With expertise in full-stack development, system design, and cloud computing, he consistently delivers high-quality, scalable solutions. Known for producing accurate and insightful technical content, Ayaan contributes valuable knowledge to the developer community.

Full Stack Developer Course Banner