Back to series
· 12 min read

Python Shallow Copy and Deep Copy


I. Why You Need to Understand Object Copying

In Python, variables don't store the object itself — they store a reference to the object. When multiple variables point to the same object, modifying the object through one variable is also observed through the others.

For example:

user = {
    "name": "Alice",
    "profile": {
        "age": 25,
        "city": "Tokyo"
    }
}

another_user = user

another_user["name"] = "Bob"

print(user["name"])  # Bob

No new dictionary is created here — user and another_user point to the same object.

If you want to create an independent copy, you need to use a copy operation.

But there is more than one way to copy:

  • Direct assignment: does not copy the object, only the reference.
  • Shallow Copy: creates a new object, but the inner elements may still share references.
  • Deep Copy: recursively copies the object and its inner members, building an independent object structure as much as possible.

Understanding these three approaches is the foundation for correctly handling lists, dictionaries, nested objects, and complex data structures.

II. Python Object References and Their Relationship with Memory

1. Variables and Objects

In Python, a variable is essentially a name binding to an object.

a = [1, 2, 3]
b = a

print(a is b)  # True
print(id(a) == id(b))  # True

a and b point to the same list object.

You can use the following tools to observe object relationships:

Tool Purpose
id(obj) Returns the object's identity
is Determines whether two references point to the same object
== Determines whether the values of two objects are equal
type(obj) Checks the object's type
sys.getrefcount(obj) Checks the approximate reference count in CPython

Note: id() returns the object's identity. In CPython this usually corresponds to the object's memory address, but the Python language specification does not require all implementations to use memory addresses.

2. Object Sharing and Modification

When multiple variables point to the same mutable object, any one reference can modify that object.

numbers = [10, 20, 30]
alias = numbers

alias.append(40)

print(numbers)
# [10, 20, 30, 40]

This phenomenon is called object sharing.

If you want to modify a copy without affecting the original object, you need to actually create a new object.

3. Mutable and Immutable Objects

Before understanding copying, you need to distinguish between mutable and immutable objects.

Type Mutable? Example
list Mutable [1, 2, 3]
dict Mutable {"name": "Alice"}
set Mutable {1, 2, 3}
bytearray Mutable bytearray(b"abc")
tuple Immutable (1, 2, 3)
str Immutable "hello"
int Immutable 100
float Immutable 3.14
frozenset Immutable frozenset({1, 2})

Immutable objects cannot have their state modified in place, but they can still be referenced by multiple objects.

In addition, although tuples are immutable, they can internally contain mutable objects such as lists:

data = (
    "Alice",
    [10, 20, 30]
)

data[1].append(40)

print(data)
# ('Alice', [10, 20, 30, 40])

Therefore, you cannot simply assume that all objects inside an immutable container are also immutable.

III. Direct Assignment: Copying the Reference, Not the Object

Direct assignment is the form most easily mistaken for a copy operation.

original = [1, 2, 3]
copied = original

copied.append(4)

print(original)
# [1, 2, 3, 4]

print(copied)
# [1, 2, 3, 4]

print(original is copied)
# True

The assignment operation only creates a new name binding; it does not create a new list object.

1. Memory relationships

original = [1, 2, 3]
copied = original

Object relationships:

original ──┐
           ├──> [1, 2, 3]
copied ────┘

2. Characteristics of direct assignment

  • Does not create a new list or dictionary object.
  • The two variables share the same object.
  • If the object is modified through any reference, the change will be visible through the other references.
  • Assignment operations usually have very low overhead.

3. When to use direct assignment

When you explicitly want multiple variables to share the same object, you can use direct assignment.

For example:

config = {
    "debug": True,
    "timeout": 30
}

current_config = config

If current_config is just another access point rather than an independent copy, then direct assignment is reasonable.

IV. What Is a Shallow Copy

A shallow copy means:

Create a new outer object, but do not recursively copy the inner members; the inner members still reference the original objects.

For example:

import copy

original = [
    1,
    2,
    [3, 4]
]

copied = copy.copy(original)

print(original is copied)
# False

The outer lists are now two different objects.

However, the nested inner list is still the same object:

print(original[2] is copied[2])
# True

1. Object relationships in a shallow copy

Original data:

original = [
    1,
    2,
    [3, 4]
]

Perform a shallow copy:

copied = copy.copy(original)

Object relationships:

original ──> [ 1, 2, ──┐ ]
                         ├──> [3, 4]
copied ────> [ 1, 2, ──┘ ]

The outer lists are independent; the inner lists are shared.

2. Modifying an outer element

import copy

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

copied[0] = 100

print(original)
# [1, 2, [3, 4]]

print(copied)
# [100, 2, [3, 4]]

Why did the original object not change?

Because copied[0] = 100 modifies the element reference in the new list; it does not modify the original list.

3. Modifying a nested inner object

import copy

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

copied[2].append(5)

print(original)
# [1, 2, [3, 4, 5]]

print(copied)
# [1, 2, [3, 4, 5]]

Why did the original object also change?

Because original[2] and copied[2] point to the same inner list.

4. Core characteristics of shallow copy

Feature Shallow copy
Creates a new outer object Yes
Copies inner member objects No
Recursively copies nested structures No
Shares mutable inner objects Yes
Do modifications to the outer structure affect each other? Usually not
Do modifications to shared inner objects affect each other? Yes

“Usually” is used here because custom containers may implement special copy behavior, but for common lists, dictionaries, and sets, the above rules apply.

V. Common Ways to Implement Shallow Copy in Python

Python provides several ways to perform a shallow copy.

1. Using copy.copy()

copy is a Python standard library module.

import copy

original = [1, 2, [3, 4]]

copied = copy.copy(original)

print(copied)
# [1, 2, [3, 4]]

print(original is copied)
# False

This is suitable for scenarios where you want to copy different types of objects through a unified interface.

2. Using list slicing

original = [1, 2, [3, 4]]

copied = original[:]

print(original is copied)
# False

print(original[2] is copied[2])
# True

List slicing creates a new list, but the inner elements still share references.

3. Using list()

original = [1, 2, [3, 4]]

copied = list(original)

print(original is copied)
# False

print(original[2] is copied[2])
# True

list() creates a new list and takes element references from the original iterable.

4. Using list.copy()

original = [1, 2, [3, 4]]

copied = original.copy()

print(original is copied)
# False

list.copy() is a shallow copy method provided by the list type.

5. Using dictionary copy()

original = {
    "name": "Alice",
    "profile": {
        "age": 25
    }
}

copied = original.copy()

print(original is copied)
# False

print(original["profile"] is copied["profile"])
# True

The dictionary's copy() also copies only the outer dictionary.

6. Using set copy()

original = {
    "Python",
    "Java",
    "Go"
}

copied = original.copy()

print(original is copied)
# False

The set's copy() creates a new set object.

Note that set elements must be hashable, so lists or dictionaries cannot be used directly as set elements.

7. Comparison of common shallow copy methods

Object Shallow copy method
List copy.copy(obj)
List obj.copy()
List obj[:]
List list(obj)
Dictionary copy.copy(obj)
Dictionary obj.copy()
Dictionary dict(obj)
Set copy.copy(obj)
Set obj.copy()
Set set(obj)

In common built-in container scenarios, these methods can all create a new outer container, but for custom types, the copy behavior may be affected by constructors and the copy protocol.

VI. What Is a Deep Copy?

A deep copy means:

Creating a new object and recursively copying the members inside it, so that the copied result shares as few mutable inner objects as possible with the original object.

Python implements deep copy using copy.deepcopy().

For example:

import copy

original = [
    1,
    2,
    [3, 4]
]

copied = copy.deepcopy(original)

print(original is copied)
# False

print(original[2] is copied[2])
# False

Both the outer list and the inner nested list are copied.

1. Object relationships in a deep copy

original = [
    1,
    2,
    [3, 4]
]

copied = copy.deepcopy(original)

Object relationships:

original ──> [1, 2, ──> [3, 4]]

copied ────> [1, 2, ──> [3, 4]]

The two copies have independent list objects.

2. Modifying inner objects

import copy

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

copied[2].append(5)

print(original)
# [1, 2, [3, 4]]

print(copied)
# [1, 2, [3, 4, 5]]

Modifying the list inside the copied object does not affect the original object.

3. Core Characteristics of Deep Copy

Feature Deep Copy
Creates a new outer object Yes
Copies internal member objects Usually
Recursively handles nested structures Yes
Shares internal mutable objects Usually not shared
Does modifying the copied object affect the original object? Usually no
Copy cost Usually higher

Note: Deep copy does not mean copying everything unconditionally. Python handles special objects through the object copy protocol and also uses an internal memo mechanism to manage object relationships.

VII. Implementing Deep Copy in Python

1. Using copy.deepcopy()

import copy

original = {
    "name": "Alice",
    "profile": {
        "age": 25,
        "skills": ["Python", "SQL"]
    }
}

copied = copy.deepcopy(original)

print(original is copied)
# False

print(original["profile"] is copied["profile"])
# False

print(
    original["profile"]["skills"]
    is copied["profile"]["skills"]
)
# False

Deep copy recursively handles nested dictionaries and lists.

2. Deep Copying Nested Lists

import copy

original = [
    [1, 2],
    [3, 4],
    [5, 6]
]

copied = copy.deepcopy(original)

copied[0].append(100)

print(original)
# [[1, 2], [3, 4], [5, 6]]

print(copied)
# [[1, 2, 100], [3, 4], [5, 6]]

3. Deep Copying Nested Dictionaries

import copy

original = {
    "user": {
        "name": "Alice",
        "age": 25
    },
    "settings": {
        "theme": "light",
        "notifications": True
    }
}

copied = copy.deepcopy(original)

copied["user"]["age"] = 30
copied["settings"]["theme"] = "dark"

print(original)
# {
#     'user': {'name': 'Alice', 'age': 25},
#     'settings': {'theme': 'light', 'notifications': True}
# }

4. Deep Copying Mixed Data Structures

import copy

original = {
    "name": "Alice",
    "tags": {"Python", "AI"},
    "scores": [90, 95],
    "profile": {
        "city": "Tokyo",
        "languages": ["Python", "Java"]
    }
}

copied = copy.deepcopy(original)

copied["tags"].add("Database")
copied["scores"].append(100)
copied["profile"]["languages"].append("Go")

print(original)

Deep copy is suitable for data structures containing multiple levels of nested mutable objects.

VIII. Core Differences Between Shallow Copy and Deep Copy

1. Comparison Summary

Comparison dimension Direct assignment Shallow copy Deep copy
Whether a new outer object is created No Yes Yes
Whether inner objects are copied No No Usually recursively copied
Whether the outer object is shared Yes No No
Whether inner mutable objects are shared Yes Yes Usually no
Whether nested structures are independent No No Usually yes
Performance overhead Lowest Relatively low Usually relatively high
Typical approach b = a copy.copy(a) copy.deepcopy(a)

2. Determining by object identity

import copy

original = {
    "name": "Alice",
    "skills": ["Python", "SQL"]
}

assigned = original
shallow = copy.copy(original)
deep = copy.deepcopy(original)

print(assigned is original)
# True

print(shallow is original)
# False

print(deep is original)
# False

print(shallow["skills"] is original["skills"])
# True

print(deep["skills"] is original["skills"])
# False

3. Comparison of modification behavior

import copy

original = {
    "name": "Alice",
    "skills": ["Python", "SQL"]
}

assigned = original
shallow = copy.copy(original)
deep = copy.deepcopy(original)

assigned["name"] = "Bob"
shallow["name"] = "Charlie"
deep["name"] = "David"

shallow["skills"].append("Go")
deep["skills"].append("Rust")

print(original)

Result:

{
    "name": "Bob",
    "skills": ["Python", "SQL", "Go"]
}

Analysis:

  • assigned["name"] modifies the original dictionary because both are the same object.
  • shallow["name"] modifies the shallow copy's own outer dictionary.
  • deep["name"] modifies the deep copy's own outer dictionary.
  • shallow["skills"] shares a reference with the original list, so adding an element affects the original object.
  • deep["skills"] is an independent list, so modifications do not affect the original object.

4. Copy behavior flow

flowchart TD
    A["Start copying object"] --> B{"Choose copy method"}
    B --> C["Direct assignment"]
    B --> D["Shallow copy"]
    B --> E["Deep copy"]

    C --> F["Copy only the object reference"]
    D --> G["Create a new outer object"]
    E --> H["Recursively process inner members"]

    F --> I["All references share the original object"]
    G --> J["Inner members may still be shared"]
    H --> K["Inner objects are usually independent"]

    I --> L["Modifications affect each other"]
    J --> M["Modifying outer structures usually does not affect each other"]
    K --> N["Modifying copied structures usually does not affect each other"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style C fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style F fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style H fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style I fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style J fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style K fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style L fill:#FBE9E9,stroke:#D9AAAA,color:#334155
    style M fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style N fill:#E5F4EC,stroke:#A3CBB5,color:#334155

    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

9. Internal Mechanism of Deep Copy: memo Dictionary

copy.deepcopy() does not simply recursively call copy operations.

It has a very important internal mechanism: the memo dictionary.

memo is used to record objects that have already been processed and their corresponding copy results.

It mainly solves two problems:

  1. Avoid copying the same object repeatedly.
  2. Avoid infinite recursion caused by circular references.

1. Why memo Is Needed

Consider the following structure:

import copy

shared = [1, 2, 3]

original = [
    shared,
    shared
]

copied = copy.deepcopy(original)

print(copied[0] is copied[1])
# True

print(copied[0] is shared)
# False

In the original object, two positions reference the same list.

After deep copy:

  • The original list is copied.
  • The two positions still reference the same copied list.
  • The copied list and the original list are independent of each other.

This shows that deep copy not only copies objects but also preserves the original reference relationships between objects as much as possible.

2. How memo Works

flowchart TD
    A["Start deepcopy"] --> B["Check whether the object is already in memo"]
    B --> C{"Does it exist?"}
    C -->|Yes| D["Return the copy in memo directly"]
    C -->|No| E["Create or prepare a copy"]
    E --> F["Register the original object and copy in memo"]
    F --> G["Recursively process inner members"]
    G --> H["Reuse the copy of the registered object"]
    H --> I["Finish copying and return"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style H fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style I fill:#E5F4EC,stroke:#A3CBB5,color:#334155

    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

3. Handling Circular References

Python objects can form circular references.

import copy

original = []
original.append(original)

print(original[0] is original)
# True

This list contains a reference to itself.

If deep copy does not handle circular references, it can fall into infinite recursion.

Use deepcopy():

copied = copy.deepcopy(original)

print(copied is original)
# False

print(copied[0] is copied)
# True

The deep copy successfully creates a new list while preserving the self-reference relationship.

4. Why Simple Recursive Copying Is Not Enough

Suppose an object structure contains a shared reference:

shared = {
    "value": 100
}

data = {
    "left": shared,
    "right": shared
}

If memo is not used and a new copy is created every time shared is encountered, it can result in:

copied["left"] is copied["right"]
# False

This would break the shared relationship in the original object structure.

With memo, deep copy can preserve this reference topology.

Note that memo is an internal mechanism of deepcopy() and should not be treated as a persistent cache in ordinary business code.

10. Deep Copy Does Not Mean Every Object Will Be Copied

The goal of deep copy is to recursively copy an object structure, but not every object needs to be or can be copied.

1. Immutable Objects May Be Reused Directly

For immutable objects such as integers and strings, deep copy can usually return the original object directly.

import copy

number = 100
text = "Python"

copied_number = copy.deepcopy(number)
copied_text = copy.deepcopy(text)

print(copied_number is number)
print(copied_text is text)

This does not affect safety, because immutable objects cannot change their own state through normal operations.

Some immutable containers may also be reused if their internal members do not need to be copied.

Therefore, deep copy should not be understood as requiring every object to have a completely new memory address.

2. Copy Behavior of Custom Objects

Python allows custom classes to control copy behavior.

The following special methods can participate in the copy protocol:

  • __copy__(): Defines shallow copy behavior.
  • __deepcopy__(memo): Defines deep copy behavior.
  • __reduce__(): Participates in object serialization and related reconstruction mechanisms.
  • __reduce_ex__(protocol): Provides a reconstruction mechanism with a protocol version.

Example:

import copy


class User:
    def __init__(self, name, profile):
        self.name = name
        self.profile = profile

    def __copy__(self):
        return type(self)(
            self.name,
            self.profile
        )


profile = {
    "age": 25
}

user = User("Alice", profile)

copied = copy.copy(user)

print(user is copied)
# False

print(user.profile is copied.profile)
# True

Here, shallow copy behavior is customized:

  • A new User object is created.
  • name uses the original immutable string reference.
  • profile still shares the original dictionary.

3. Customizing Deep Copy Behavior

import copy class User: def __init__(self, name, profile): self.name = name self.profile = profile def __deepcopy__(self, memo): cls = type(self) copied = cls.__new__(cls) memo[id(self)] = copied copied.name = copy.deepcopy( self.name, memo ) copied.profile = copy.deepcopy( self.profile, memo ) return copied user = User( "Alice", {"age": 25} ) copied = copy.deepcopy(user) print(user is copied) # False print(user.profile is copied.profile) # False ```

There is one key detail here:

You must first put the new object into memo, and only then recursively copy its members.

This correctly handles circular references that may exist among the object's members.

Custom copy protocols need to be implemented carefully. If an object contains resources such as file handles, thread locks, or network connections, a simple copy is usually not appropriate.

XI. Copy Behavior of Special Objects

Not all Python objects are suitable for deep copying.

1. File objects

```python import copy file = open("data.txt", "w", encoding="utf-8") try: copied = copy.deepcopy(file) except Exception as exc: print(type(exc).__name__, exc) finally: file.close() ```

File objects involve operating system resources, file descriptors, and file state, and usually cannot be copied like an ordinary list.

If you need to work with the file contents independently, you should reopen the file, or read the contents and then create a new data object.

2. Function and class objects

During copy operations, functions and class objects usually do not produce new function or class definitions; the original object is reused instead.

```python import copy def greet(): return "Hello" copied = copy.deepcopy(greet) print(copied is greet) # True ```

3. Module objects

Module objects usually cannot be copied with an ordinary deep copy.

```python import copy import math try: copied = copy.deepcopy(math) except Exception as exc: print(type(exc).__name__)