What is the difference between deepcopy() and copy() in Python?

The difference between copy() and deepcopy() in Python lies in how they handle nested objects (mutable objects inside other objects like lists or dictionaries).


1. copy() (Shallow Copy)
  • Creates a new object, but references nested objects instead of copying them.
  • Changes to nested objects affect both the original and copied object.
Example :
import copy

original = [[1, 2, 3], [4, 5, 6]]
shallow_copy = copy.copy(original)

shallow_copy[0][0] = 99  # Modifying a nested list
print(original)       # Output: [[99, 2, 3], [4, 5, 6]]  (Changed!)
print(shallow_copy)   # Output: [[99, 2, 3], [4, 5, 6]]

* Best for non-nested objects or when modifying nested elements is acceptable.


2. deepcopy() (Deep Copy)
  • Creates a completely independent copy, including all nested objects.
  • Changes to the new object do not affect the original.
Example :
import copy

original = [[1, 2, 3], [4, 5, 6]]
deep_copy = copy.deepcopy(original)

deep_copy[0][0] = 99  # Modifying a nested list
print(original)      # Output: [[1, 2, 3], [4, 5, 6]]  (Unchanged!)
print(deep_copy)     # Output: [[99, 2, 3], [4, 5, 6]]

* Best for deeply nested structures where modifications should be independent.


Key Differences
Feature copy() (Shallow Copy) deepcopy() (Deep Copy)
Creates a new object? Yes Yes
Copies nested objects? No (references same objects) Yes (new copies of all objects)
Modifying nested objects affects original? Yes No
Performance Faster Slower (more memory usage)
Best for Flat structures, minimal nesting Deeply nested data