PYTHON

Safely Deep Copy Nested Data Structures in Python

Learn how to use `copy.deepcopy()` in Python to create independent copies of complex, nested data structures, preventing unintended modifications of original objects.

import copy

original_list = [
    [1, 2, 3],
    {'a': 1, 'b': [4, 5]},
    "immutable_string"
]

# Shallow copy: Copies references to nested objects
shallow_copied_list = list(original_list) # Or original_list[:] or copy.copy(original_list)

# Deep copy: Creates entirely new objects for all nested structures
deep_copied_list = copy.deepcopy(original_list)

print("--- Before Modification ---")
print(f"Original: {original_list}")
print(f"Shallow Copy: {shallow_copied_list}")
print(f"Deep Copy: {deep_copied_list}
")

# Modify a nested mutable object in the original list
original_list[0][0] = 99
original_list[1]['b'].append(6)

print("--- After Modification of Original ---")
print(f"Original: {original_list}")
print(f"Shallow Copy: {shallow_copied_list}") # Reflects changes in nested mutable objects
print(f"Deep Copy: {deep_copied_list}
") # Is unaffected

# Verify memory addresses (optional, for demonstration)
# print(f"original_list[0] id: {id(original_list[0])}")
# print(f"shallow_copied_list[0] id: {id(shallow_copied_list[0])}")
# print(f"deep_copied_list[0] id: {id(deep_copied_list[0])}")
How it works: When working with nested mutable data structures like lists of lists or dictionaries containing lists, a simple assignment or shallow copy (e.g., `list()`, `[:]`, `copy.copy()`) only copies references to the nested objects. This means modifying a nested object in the copy will also affect the original. `copy.deepcopy()` creates a fully independent replica by recursively copying all objects, ensuring that modifications to the copied structure do not impact the original.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs