Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 6 of 10 · Data Types and Data Structures
Interview question

What is the difference between shallow copy and deep copy? - Data Types and Data Structures Shallow copy और deep copy में क्या अंतर है?

Answer
import copy

# Shallow copy - copies only surface level
original = [[1, 2], [3, 4]]
shallow = copy.copy(original)

shallow[0][0] = 999
print(original)  # [[999, 2], [3, 4]] - affected!
print(shallow)   # [[999, 2], [3, 4]]

# Deep copy - copies all levels
original = [[1, 2], [3, 4]]
deep = copy.deepcopy(original)

deep[0][0] = 999
print(original)  # [[1, 2], [3, 4]] - NOT affected
print(deep)      # [[999, 2], [3, 4]]

# List copy methods
my_list = [1, 2, 3]
shallow_list = my_list.copy()  # Shallow copy
shallow_list[0] = 999
print(my_list)  # [1, 2, 3] - OK for flat lists
import copy

# Shallow copy - nested objects share references
original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
shallow[0][0] = 999
print(original)  # [[999, 2], [3, 4]] - affected!

# Deep copy - all levels copied
original = [[1, 2], [3, 4]]
deep = copy.deepcopy(original)
deep[0][0] = 999
print(original)  # [[1, 2], [3, 4]] - NOT affected

Was this answer clear?