Python Copying Techniques: Differences Between Deep and Shallow Copy

python @ Freshers.in

Understanding copying in Python is crucial for managing mutable objects and preventing unintended side effects. In this article, we’ll explore the distinctions between deep and shallow copy, unravel their implications, and provide real-world examples to empower you with the knowledge needed to choose the right copying technique for your programming tasks.

Shallow Copy: The Surface-Level Duplication

A shallow copy creates a new object but inserts references to the objects found in the original. While the outer structure is duplicated, the inner objects remain shared between the original and the copy.

import copy
original_list = [1, [2, 3], [4, 5]]
shallow_copy = copy.copy(original_list)
# Modify an element in the shallow copy
shallow_copy[1][0] = 'X'
print(original_list)
# Output: [1, ['X', 3], [4, 5]]

Deep Copy: A True Replica

A deep copy creates a new object and recursively copies all objects found in the original. It results in a completely independent duplicate, ensuring changes in the copy do not affect the original.

import copy
original_list = [1, [2, 3], [4, 5]]
deep_copy = copy.deepcopy(original_list)
# Modify an element in the deep copy
deep_copy[1][0] = 'X'
print(original_list)
# Output: [1, [2, 3], [4, 5]]

Real-World Example: Copying Complex Objects

Consider a scenario where you have a nested dictionary representing a configuration. We’ll explore how shallow and deep copy behave in this context.

import copy
original_config = {'user': 'Alice', 'settings': {'theme': 'dark', 'font_size': 12}}
shallow_copy = copy.copy(original_config)
deep_copy = copy.deepcopy(original_config)
# Modify elements in the copies
shallow_copy['settings']['font_size'] = 14
deep_copy['settings']['font_size'] = 16
print(original_config)
# Output: {'user': 'Alice', 'settings': {'theme': 'dark', 'font_size': 12}}

Choosing the Right Copying Technique

  • Use Shallow Copy When: You want a new object with a top-level duplication, and inner objects can remain shared. It’s more memory-efficient and faster.
  • Use Deep Copy When: You need a completely independent duplicate, ensuring changes in the copy do not affect the original. Suitable for complex nested structures.

Refer more on python here :

Author: Freshers