160. Deep Copy vs Shallow Copy

Snippet 1: Shallow Copy Using copy() Method

Copy

import copy

# Original list with nested list
original_list = [1, 2, [3, 4]]

# Shallow copy
shallow_copy = original_list.copy()

# Modifying the nested list in the shallow copy
shallow_copy[2][0] = 99

print(f"Original list: {original_list}")
print(f"Shallow copy: {shallow_copy}")

Snippet 2: Shallow Copy Using copy.copy()

Copy

import copy

# Original dictionary with nested dictionary
original_dict = {'a': 1, 'b': {'c': 2}}

# Shallow copy
shallow_copy = copy.copy(original_dict)

# Modifying the nested dictionary in the shallow copy
shallow_copy['b']['c'] = 99

print(f"Original dict: {original_dict}")
print(f"Shallow copy: {shallow_copy}")

Snippet 3: Deep Copy Using copy.deepcopy()

Copy


Snippet 4: Comparing Shallow and Deep Copy

Copy


Snippet 5: Shallow Copy of a Nested List

Copy


Snippet 6: Shallow Copy of a Dictionary

Copy


Snippet 7: Creating a Deep Copy with a Custom Class

Copy


Snippet 8: Shallow Copy and Identity

Copy


Snippet 9: Deep Copy and Identity

Copy


Snippet 10: When to Use Shallow Copy vs Deep Copy

Copy


Last updated