Fundamentals 14 min read

Master Python Deep vs Shallow Copy: Definitions, Memory Efficiency & Use Cases

This article explains Python's shallow and deep copy mechanisms, detailing their definitions, implementation methods, memory implications, and practical scenarios, supplemented with clear analogies, code examples, and performance considerations to help developers choose the appropriate copying technique.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Master Python Deep vs Shallow Copy: Definitions, Memory Efficiency & Use Cases

Overview

Detailed explanation of Python deep copy and shallow copy, covering definitions, differences, implementation methods, memory efficiency, and practical application scenarios.

1. Simple Explanation

What is a shallow copy?

A shallow copy is like copying a business card: it duplicates the surface information of an object, creating a new object that may still share some internal parts (e.g., nested objects). Modifying those shared parts affects both the original and the copy.

What is a deep copy?

A deep copy is like copying an entire house: it duplicates not only the surface but also all nested objects recursively, resulting in a completely independent new object.

Analogy

Shallow copy: copying a book’s cover and table of contents while the content still points to the original pages. Deep copy: photocopying the whole book, including every page, creating an entirely separate book.

2. Academic Explanation

In Python, copying creates a duplicate of an object to avoid modifying the original. Objects are either mutable (list, dict, set) or immutable (int, str, tuple). Copy behavior varies with object type and copy method.

Shallow Copy (Shallow Copy)

Definition: Creates a new object but copies only references to the top‑level elements; nested mutable objects remain shared.

Implementation methods:

copy.copy() (copy module)

Slicing (e.g., list[:])

list.copy(), dict.copy()

Characteristics: Only the top‑level object is duplicated; nested objects are shared. Modifying the top level does not affect the original, but changes to nested objects affect both.

Memory efficiency: Low memory overhead because only the top‑level structure is copied.

Deep Copy (Deep Copy)

Definition: Creates a completely independent new object by recursively copying the object and all its nested sub‑objects.

Implementation method: copy.deepcopy() (copy module)

Characteristics: The entire object tree is duplicated; modifications to any part of the copy never affect the original.

Memory efficiency: Higher memory usage because all nested objects are duplicated.

Key Differences

Python Object Model

Mutable objects (list, dict, set) share references when copied; immutable objects (int, str, tuple) create new objects on assignment. Variable assignment copies references, not the objects themselves.

3. Code Examples

Example 1: Shallow Copy with Nested List

import copy
# Original object: nested list
original = [1, 2, [3, 4]]
# Shallow copy
shallow = copy.copy(original)
# Modify top‑level element
shallow[0] = 100
print("After modifying shallow[0]:")
print("Original:", original)  # Original: [1, 2, [3, 4]]
print("Shallow:", shallow)    # Shallow: [100, 2, [3, 4]]
# Modify nested object
shallow[2].append(5)
print("
After modifying shallow[2]:")
print("Original:", original)  # Original: [1, 2, [3, 4, 5]]
print("Shallow:", shallow)    # Shallow: [100, 2, [3, 4, 5]]

Example 2: Deep Copy with Nested Dictionary

import copy
# Original object: nested dict
original = {"a": 1, "b": {"x": 10, "y": 20}}
# Deep copy
deep = copy.deepcopy(original)
# Modify top‑level element
deep["a"] = 100
print("After modifying deep['a']:")
print("Original:", original)  # Original: {'a': 1, 'b': {'x': 10, 'y': 20}}
print("Deep:", deep)          # Deep: {'a': 100, 'b': {'x': 10, 'y': 20}}
# Modify nested object
deep["b"]["x"] = 999
print("
After modifying deep['b']['x']:")
print("Original:", original)  # Original unchanged
print("Deep:", deep)          # Deep reflects change only

Example 3: Comparing Shallow Copy Methods

# Original list
original = [1, 2, [3, 4]]
# Different shallow copy approaches
slice_copy = original[:]
list_copy = original.copy()
copy_copy = copy.copy(original)
# Modify nested object
slice_copy[2].append(5)
print("Original:", original)       # Original: [1, 2, [3, 4, 5]]
print("Slice Copy:", slice_copy)   # Slice Copy: [1, 2, [3, 4, 5]]
print("List Copy:", list_copy)     # List Copy: [1, 2, [3, 4, 5]]
print("Copy Copy:", copy_copy)     # Copy Copy: [1, 2, [3, 4, 5]]

Example 4: Immutable Objects and Copy

import copy
# Original object: contains immutable string and mutable list
original = ["hello", [1, 2]]
# Shallow and deep copies
shallow = copy.copy(original)
deep = copy.deepcopy(original)
# Modify mutable part
shallow[1].append(3)
print("After modifying shallow[1]:")
print("Original:", original)  # ['hello', [1, 2, 3]]
print("Shallow:", shallow)    # ['hello', [1, 2, 3]]
print("Deep:", deep)          # ['hello', [1, 2]]
# Attempt to modify immutable part
shallow[0] = "world"
print("
After modifying shallow[0]:")
print("Original:", original)  # unchanged string
print("Shallow:", shallow)    # string replaced in shallow copy
print("Deep:", deep)          # deep unchanged

Example 5: Singleton and Copy

import copy
class Singleton:
    _instance = None
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance

s1 = Singleton()
s2 = copy.deepcopy(s1)  # Deep copy may break singleton
print(s1 is s2)  # False, deep copy creates a new object

4. Memory Efficiency Analysis

import copy
import sys
original = [1, 2, [3, 4, [5, 6]]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)
print(sys.getsizeof(original))  # Approx. 88 bytes (top‑level only)
print(sys.getsizeof(shallow))   # Approx. 88 bytes (top‑level copy)
print(sys.getsizeof(deep))      # Approx. 88 bytes (top‑level), but actual memory includes all nested objects

Note: sys.getsizeof reports only the size of the top‑level container; deep copies allocate additional memory for nested objects.

5. Application Scenarios

Shallow Copy

Temporary copies where only top‑level modifications are needed.

Performance‑critical code with large data where nested objects need not be altered.

Data processing such as quick list sorting or filtering.

Deep Copy

Creating completely independent backups (e.g., configuration objects).

Handling complex nested structures like JSON data or graphical objects.

Testing and debugging to ensure test data does not affect original data.

6. Relation to Closures, Decorators, and Singletons

Closures may copy configuration objects to avoid external mutation. Decorators can use deep copies to cache independent results. In singleton patterns, copying can unintentionally create new instances, so __deepcopy__ should be overridden or copying disabled.

7. Precautions

Be aware that shallow copies share nested mutable objects, which can cause unexpected side effects.

Deep copies on large structures may incur significant CPU and memory overhead.

Copying immutable objects is usually unnecessary.

Custom classes may need __copy__ and __deepcopy__ implementations.

Circular references are handled by copy.deepcopy automatically.

8. Summary

Shallow copy duplicates only the top‑level object; nested objects remain shared, offering low memory usage.

Deep copy recursively duplicates the entire object tree, providing full isolation at higher memory cost.

Use copy.copy(), slicing, or .copy() for shallow copies; use copy.deepcopy() for deep copies.

Choose the copying strategy based on the need for isolation versus performance.

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 Examplesdeep copymemory efficiencyshallow copy
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

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.