Python #591
Answered
by
TatyOko28
houstonTaleubou
asked this question in
Q&A
Python
#591
-
What is the difference between deepcopy() and copy() in Python? |
Beta Was this translation helpful? Give feedback.
Answered by
TatyOko28
Feb 8, 2025
Replies: 1 comment 1 reply
-
copy.copy() creates a shallow copy, meaning it only copies the references to nested objects instead of duplicating them. If the original object contains mutable objects (like lists or dictionaries), changes to the original will affect the copy. import copy
list1 = [[1, 2, 3], [4, 5, 6]]
shallow = copy.copy(list1)
deep = copy.deepcopy(list1)
list1[0][0] = 100 # Modify original list
print(shallow) # [[100, 2, 3], [4, 5, 6]] (Affected)
print(deep) # [[1, 2, 3], [4, 5, 6]] (Unaffected) |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
houstonTaleubou
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
copy.copy() creates a shallow copy, meaning it only copies the references to nested objects instead of duplicating them. If the original object contains mutable objects (like lists or dictionaries), changes to the original will affect the copy.
copy.deepcopy() creates a deep copy, meaning it recursively copies all objects, ensuring that modifying the original does not affect the copy.
Example: