Learn with Yasir

Share Your Feedback

Deep Copy in Python – Explained with Examples and Comparison


Learn what a deep copy is in Python, how it differs from a shallow copy, and when to use it. Includes simple explanations, beginner-friendly code examples, and use cases for nested lists and dictionaries.

Table of Contents

  1. What is a Deep Copy in Python?
  2. Why Use Deep Copy?
  3. How to Make a Deep Copy?
  4. Beginner-Friendly Example
  5. Comparison: Shallow vs Deep Copy
  6. Another Example: Dictionary with Nested List

1. 🧠 What is a Deep Copy in Python?

A deep copy creates a completely independent copy of an object and all nested objects inside it.

Changes made to the original object do not affect the deep copy, and vice versa.


2. ✅ Why Use Deep Copy?

When your object contains nested structures like:

  • Lists of lists
  • Dictionaries of dictionaries
  • Objects containing other objects

…and you want totally independent copies, use deep copy.


3. 📦 How to Make a Deep Copy?

Use the copy module:

import copy

deep_copy_object = copy.deepcopy(original_object)

4. 🔍 Beginner-Friendly Example:

import copy

original = [[1, 2], [3, 4]]
deep = copy.deepcopy(original)

# Modify deep copy
deep[0][0] = 100

print("Original:", original)  # Output: [[1, 2], [3, 4]]
print("Deep Copy:", deep)     # Output: [[100, 2], [3, 4]]

✅ Here, changing deep[0][0] does not affect the original list.


5. 🔁 Comparison: Shallow vs Deep Copy

Feature Shallow Copy (copy.copy()) Deep Copy (copy.deepcopy())
Copies top-level
Copies nested ❌ (references only) ✅ (real copies)
Independent?

6. 🧪 Another Example: Dictionary with Nested List

import copy

original = {'a': [1, 2]}
deep = copy.deepcopy(original)

deep['a'][0] = 100

print("Original:", original)  # {'a': [1, 2]}
print("Deep Copy:", deep)     # {'a': [100, 2]}
  • What is a Shallow Copy – In Python, a shallow copy is a new object that is a copy of the original object, but it does not create copies of nested objects (objects inside objects). 👉 Learn more

🧠 Practice & Progress

Explore More Topics

📘 Learn Python

Tutorials, Roadmaps, Bootcamps & Visualization Projects

Python Fundamentals

Flow Control Statements


Python Functions


Fundamentals more ...




🧠 Python Advanced

Object-Oriented Programming in Python (OOP)

More...

🧠 Modules