When to Use copy() or deepcopy():
2024
If you want to create an independent copy of mutable objects (like lists, dictionaries), use the following:
- Shallow Copy (
copy
):- Creates a new object but only copies the references of nested mutable elements.
- Changes to nested objects reflect in the copy.
import copy original = [1, [2, 3]] shallow = copy.copy(original) shallow[1][0] = 99 print(original) # Output: [1, [99, 3]]
- Deep Copy (
deepcopy
):- Creates a new object and recursively copies all nested objects. Changes in the copied object do not affect the original.
import copy original = [1, [2, 3]] deep = copy.deepcopy(original) deep[1][0] = 99 print(original) # Output: [1, [2, 3]]
Summary:
- Immutable objects like strings, integers, and tuples don’t require explicit copying because they can’t be modified.
- Mutable objects like lists, dictionaries, and sets require careful handling if you need independent copies. Use
copy.copy()
orcopy.deepcopy()
when appropriate.
examples:
import copy
original = [1, [2, 3]]
shallow = copy.copy(original)
shallow[1][0] = 99
print(original) # Output: [1, [99, 3]]
or_l = [1, [2, 3]]
shal_l = or_l
shal_l[1][0] = 99
print(or_l)
or_dic = {"name":"Anne", "age":12}
shal_dic = or_dic
or_dic['name'] = "Test"
print(or_dic)
Output:
[1, [99, 3]]
[1, [99, 3]]
{'name': 'Test', 'age': 12}