2 min read

Shallow Copy vs. Deep Copy in Python

Shallow Copy vs. Deep Copy in Python
Photo by Mohammad Rahmani / Unsplash

In Python, when you create a copy of an object, you're essentially creating a new reference to the same underlying data. This can lead to unexpected behavior, especially when dealing with nested data structures. To address this, Python provides two types of copying: shallow copy and deep copy.

Shallow Copy

  • Definition: Creates a new object but shares the references to the original object's internal objects.
  • Implementation: Using the copy.copy() function from the copy module.
  • When to Use: When you have simple objects or don't want to create entirely independent copies of nested objects.
  • Example:
import copy

original_list = [1, 2, [3, 4]]
shallow_copy = copy.copy(original_list)

shallow_copy[0] = 10  # Modifies the first element of both lists
shallow_copy[2][0] = 30  # Modifies the nested list in both copies

Deep Copy

  • Definition: Creates a new object and recursively copies all nested objects.
  • Implementation: Using the copy.deepcopy() function from the copy module.
  • When to Use: When you need to create an entirely independent copy of an object and its nested objects.
  • Example:
import copy

original_list = [1, 2, [3, 4]]
deep_copy = copy.deepcopy(original_list)

deep_copy[0] = 10  # Modifies only the first element of the deep copy
deep_copy[2][0] = 30  # Modifies only the nested list in the deep copy

Key Differences:

FeatureShallow CopyDeep Copy
Object CreationCreates a new objectCreates a new object and recursively copies nested objects
Memory UsageLess memory-intensiveMore memory-intensive
Modification ImpactChanges to the original object can affect the copyChanges to the original object do not affect the copy

In Summary:

  • Use shallow copy when you want to create a new object that shares references to the original object's internal objects. This is useful for simple objects or when you don't mind if changes to the original object affect the copy.
  • Use deep copy when you need to create an entirely independent copy of an object and its nested objects. This is useful for complex data structures where you want to avoid unintended side effects.

By understanding the distinction between shallow and deep copies, you can effectively manage object references and prevent unexpected behavior in your Python programs.