Skip to content

Python #591

Answered by TatyOko28
houstonTaleubou asked this question in Q&A
Feb 8, 2025 · 1 comments · 1 reply
Discussion options

You must be logged in to vote

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:

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)

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@AvotraRNV
Comment options

Answer selected by houstonTaleubou
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants