PyData Careers
20.9K subscribers
207 photos
4 videos
26 files
352 links
Python Data Science jobs, interview tips, and career insights for aspiring professionals.

Admin: @HusseinSheikho || @Hussein_Sheikho
Download Telegram
Question:
What are the differences between shallow copy and deep copy in Python, and when can using a shallow copy lead to unexpected behavior? Provide an example illustrating this.

Answer:
A shallow copy creates a new object but inserts references to the items found in the original object. A deep copy creates a new object and recursively copies all objects found in the original, meaning that the copy and original are fully independent.

Using a shallow copy can lead to unexpected behavior when the original object contains nested mutable objects because changes to nested objects in the copy will reflect in the original.

Example demonstrating the issue:
import copy

original = [[1, 2], [3, 4]]
shallow_copy = copy.copy(original)
shallow_copy.append(99)

print("Original:", original) # Outputs: [[1, 2, 99], [3, 4]]
print("Shallow Copy:", shallow_copy) # Outputs: [[1, 2, 99], [3, 4]]


Notice that modifying the nested list in the shallow copy also affected the original.

How to avoid this:
Use deepcopy from the copy module to create a fully independent copy:
deep_copy = copy.deepcopy(original)
deep_copy.append(100)

print("Original:", original) # Outputs: [[1, 2, 99], [3, 4]]
print("Deep Copy:", deep_copy) # Outputs: [[1, 2, 99, 100], [3, 4]]


#Python #Advanced #ShallowCopy #DeepCopy #MutableObjects #CopyModule
2👍1