Fundamentals 8 min read

Understanding Shallow Copy and Deep Copy in Python with Examples

This article explains the concepts of shallow copy and deep copy in Python, describes their differences, and provides numerous code examples—including lists, dictionaries, and custom classes—to demonstrate how to use the copy module’s copy and deepcopy functions effectively.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Understanding Shallow Copy and Deep Copy in Python with Examples

When you need to duplicate an object, copying its reference is often insufficient; you must create an independent copy. This is where shallow copy and deep copy become essential.

Shallow Copy creates a new object and fills it with references to the original object's elements; immutable types are effectively duplicated, while mutable types retain references.

Deep Copy creates a new object and recursively copies all objects found within the original, producing a fully independent clone.

Example Code

First, import the copy module, which provides the copy and deepcopy functions.

1. Shallow copy of a list

import copy</code><code>original_list = [1, 2, [3, 4]]</code><code>shallow_copied_list = copy.copy(original_list)</code><code>original_list.append(5)</code><code>original_list[2].append(6)</code><code>print("Original List:", original_list)  # Output: [1, 2, [3, 4, 6], 5]</code><code>print("Shallow Copied List:", shallow_copied_list)  # Output: [1, 2, [3, 4, 6]]

2. Deep copy of a list

import copy</code><code>original_list = [1, 2, [3, 4]]</code><code>deep_copied_list = copy.deepcopy(original_list)</code><code>original_list.append(5)</code><code>original_list[2].append(6)</code><code>print("Original List:", original_list)  # Output: [1, 2, [3, 4, 6], 5]</code><code>print("Deep Copied List:", deep_copied_list)  # Output: [1, 2, [3, 4]]

3. Shallow copy of a dictionary

import copy</code><code>original_dict = {'a': 1, 'b': 2, 'c': [3, 4]}</code><code>shallow_copied_dict = copy.copy(original_dict)</code><code>original_dict['c'].append(5)</code><code>print("Original Dict:", original_dict)  # Output: {'a': 1, 'b': 2, 'c': [3, 4, 5]}</code><code>print("Shallow Copied Dict:", shallow_copied_dict)  # Output: {'a': 1, 'b': 2, 'c': [3, 4, 5]}

4. Deep copy of a dictionary

import copy</code><code>original_dict = {'a': 1, 'b': 2, 'c': [3, 4]}</code><code>deep_copied_dict = copy.deepcopy(original_dict)</code><code>original_dict['c'].append(5)</code><code>print("Original Dict:", original_dict)  # Output: {'a': 1, 'b': 2, 'c': [3, 4, 5]}</code><code>print("Deep Copied Dict:", deep_copied_dict)  # Output: {'a': 1, 'b': 2, 'c': [3, 4]}

5. Shallow copy of a custom class

import copy</code><code>class MyClass:</code><code>    def __init__(self, value):</code><code>        self.value = value</code><code>original_obj = MyClass([1, 2, 3])</code><code>shallow_copied_obj = copy.copy(original_obj)</code><code>original_obj.value.append(4)</code><code>print("Original Value:", original_obj.value)  # Output: [1, 2, 3, 4]</code><code>print("Shallow Copied Value:", shallow_copied_obj.value)  # Output: [1, 2, 3, 4]

6. Deep copy of a custom class

import copy</code><code>class MyClass:</code><code>    def __init__(self, value):</code><code>        self.value = value</code><code>original_obj = MyClass([1, 2, 3])</code><code>deep_copied_obj = copy.deepcopy(original_obj)</code><code>original_obj.value.append(4)</code><code>print("Original Value:", original_obj.value)  # Output: [1, 2, 3, 4]</code><code>print("Deep Copied Value:", deep_copied_obj.value)  # Output: [1, 2, 3]

7. Defining a custom __copy__ method

import copy</code><code>class MyClass:</code><code>    def __init__(self, value):</code><code>        self.value = value</code><code>    def __copy__(self):</code><code>        return MyClass(self.value[:])</code><code>original_obj = MyClass([1, 2, 3])</code><code>shallow_copied_obj = copy.copy(original_obj)</code><code>original_obj.value.append(4)</code><code>print("Original Value:", original_obj.value)  # Output: [1, 2, 3, 4]</code><code>print("Shallow Copied Value:", shallow_copied_obj.value)  # Output: [1, 2, 3]

8. Defining a custom __deepcopy__ method

import copy</code><code>class MyClass:</code><code>    def __init__(self, value):</code><code>        self.value = value</code><code>    def __deepcopy__(self, memo):</code><code>        return MyClass(copy.deepcopy(self.value, memo))</code><code>original_obj = MyClass([1, 2, 3])</code><code>deep_copied_obj = copy.deepcopy(original_obj)</code><code>original_obj.value.append(4)</code><code>print("Original Value:", original_obj.value)  # Output: [1, 2, 3, 4]</code><code>print("Deep Copied Value:", deep_copied_obj.value)  # Output: [1, 2, 3]

9. Shallow copy of a complex structure

import copy</code><code>original_complex = [1, 2, [3, 4], {'a': 5, 'b': [6, 7]}]</code><code>shallow_copied_complex = copy.copy(original_complex)</code><code>original_complex[2].append(8)</code><code>original_complex[3]['b'].append(9)</code><code>print("Original Complex:", original_complex)  # Output: [1, 2, [3, 4, 8], {'a': 5, 'b': [6, 7, 9]}]</code><code>print("Shallow Copied Complex:", shallow_copied_complex)  # Output: [1, 2, [3, 4, 8], {'a': 5, 'b': [6, 7, 9]}]

10. Deep copy of a complex structure

import copy</code><code>original_complex = [1, 2, [3, 4], {'a': 5, 'b': [6, 7]}]</code><code>deep_copied_complex = copy.deepcopy(original_complex)</code><code>original_complex[2].append(8)</code><code>original_complex[3]['b'].append(9)</code><code>print("Original Complex:", original_complex)  # Output: [1, 2, [3, 4, 8], {'a': 5, 'b': [6, 7, 9]}]</code><code>print("Deep Copied Complex:", deep_copied_complex)  # Output: [1, 2, [3, 4], {'a': 5, 'b': [6, 7]}]

These examples demonstrate that a shallow copy only duplicates the top‑level structure, while a deep copy recursively clones all nested objects, ensuring complete independence between the original and the copy.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonCode ExamplesObject Cloningshallow copy
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.