Fundamentals 11 min read

Master Python Shallow vs Deep Copy: Using copy.copy() and copy.deepcopy()

This article explains Python's assignment operator behavior, demonstrates why it creates shared references rather than true copies, and provides detailed examples of shallow and deep copying using the copy module, including code snippets, output analysis, and practical scenarios such as data processing and game development.

Code Mala Tang
Code Mala Tang
Code Mala Tang
Master Python Shallow vs Deep Copy: Using copy.copy() and copy.deepcopy()

In Python the = operator creates a new variable that shares the same reference as the original object, not a true copy.

Example 1: Using = for copying

old_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
new_list = old_list
new_list[2][2] = 9
print('Old List:', old_list)
print('ID of Old List:', id(old_list))
print('New List:', new_list)
print('ID of New List:', id(new_list))

The output shows that old_list and new_list have the same id, meaning they reference the same object; changes to one affect the other.

To create independent copies you can use the copy module, which provides two functions:

copy() : returns a shallow copy of the object.

deepcopy() : returns a deep copy, recursively copying nested objects.

Copy Module

Import the module with import copy and then call copy.copy(x) for a shallow copy or copy.deepcopy(x) for a deep copy.

Shallow Copy

A shallow copy creates a new container object but stores references to the original elements.

Example 2: Shallow copy of a list

import copy
old_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
new_list = copy.copy(old_list)
print('Old list:', old_list)
print('New list:', new_list)

Both lists look identical, yet they share references to the inner lists.

Example 3: Adding a nested object to the original list

import copy
old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
new_list = copy.copy(old_list)
old_list.append([4, 4, 4])
print('Old list:', old_list)
print('New list:', new_list)

The new nested list appears only in old_list; new_list remains unchanged because the outer container was copied.

Example 4: Modifying a nested element

import copy
old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
new_list = copy.copy(old_list)
old_list[1][1] = 'AA'
print('Old list:', old_list)
print('New list:', new_list)

Both lists show the change because they share the same inner lists.

Deep Copy

A deep copy creates a completely independent object, recursively copying all nested objects.

Example 5: Deep copy of a list

import copy
old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
new_list = copy.deepcopy(old_list)
print('Old list:', old_list)
print('New list:', new_list)

Modifying old_list after this does not affect new_list.

Example 6: Changing a nested element in the original

import copy
old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
new_list = copy.deepcopy(old_list)
old_list[1][0] = 'BB'
print('Old list:', old_list)
print('New list:', new_list)

The deep‑copied new_list remains unchanged, confirming full independence.

Shallow vs Deep Copy: Key Differences

Shallow copy : creates a new container, but nested objects are still references to the original; changes to nested objects affect both copies. Use copy.copy().

Deep copy : creates a new container and recursively copies all nested objects; modifications to the original do not affect the copy. Use copy.deepcopy().

Practical Use Cases

Scenario 1: Data Processing

When handling complex data structures (e.g., lists of dictionaries), a deep copy ensures the original data remains unchanged while you manipulate a copy.

import copy
user_data = [
    {"name": "Alice", "age": 25, "address": {"city": "New York", "zip": "10001"}},
    {"name": "Bob", "age": 30, "address": {"city": "Los Angeles", "zip": "90001"}}
]
user_data_copy = copy.deepcopy(user_data)
user_data[0]["address"]["city"] = "Chicago"
print('Original Data:', user_data)
print('Copied Data:', user_data_copy)

The copied data retains the original city values, demonstrating the effectiveness of deep copying.

Scenario 2: Game Development

Duplicating game object states for different scenes requires deep copies to avoid unintended cross‑scene mutations.

import copy
game_object = {
    "position": {"x": 0, "y": 0},
    "health": 100,
    "inventory": ["sword", "shield"]
}
game_object_copy = copy.deepcopy(game_object)
# Modify original
game_object["position"]["x"] = 10
game_object["inventory"].append("potion")
print('Original Game Object:', game_object)
print('Copied Game Object:', game_object_copy)

The copy retains the original position and inventory, confirming isolation.

Conclusion

In Python, shallow and deep copies serve different purposes. Use copy.copy() for lightweight copies when nested objects can be shared, and copy.deepcopy() when you need a fully independent duplicate, such as in data processing pipelines or game state management.

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.

Pythondeep copycopy moduleshallow copylist duplication
Code Mala Tang
Written by

Code Mala Tang

Read source code together, write articles together, and enjoy spicy hot pot together.

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.