What is difference between copy() and deepcopy() in Python
-
In Python,
copy
anddeepcopy
come from thecopy
module and are used to duplicate objects.The key difference lies in how they handle nested objects.
1. Shallow Copy (
copy.copy()
)Creates a new object but does not recursively copy nested objects (like
list
s ordict
s inside the object).If the original object contains mutable objects (
list
s,dict
s, etc.), modifications to those mutables in the copied object will affect the original.import copy original = [1, [2, 3], 4] shallow_copy = copy.copy(original) shallow_copy[1][0] = 99 # Modifies the nested list print(original) # Output: [1, [99, 3], 4]
Explanation: Since copy.copy() only creates a new top-level object but keeps references to inner objects, changes in the nested list
shallow_copy[1]
reflect in the original.2. Deep Copy (
copy.deepcopy()
)Creates a new object and recursively copies all nested objects.
Modifications in the copied object will not affect the original.deep_copy = copy.deepcopy(original) deep_copy[1][0] = 42 print(original) # Output: [1, [99, 3], 4] (unchanged)
Explanation:
deepcopy()
creates an entirely independent copy of the object, including all nested elements.3. When to Use?
Use
copy.copy()
when your object only contains immutable elements (like numbers, strings, tuples) or when shallow copying is sufficient.Use
copy.deepcopy()
when your object contains nested mutable objects and you want a fully independent copy.