QA
Beginner LevelPython

What is the difference between a Shallow Copy and a Deep Copy in Python?

❓ Interview Prompt: Explain `copy.copy()` (shallow copy, nested references shared) vs `copy.deepcopy()` (recursively duplicates nested objects).

When copying compound objects (lists/dicts containing other lists/dicts):

1. Shallow Copy ('copy.copy(obj)' or 'obj.copy()'):

Creates a new container object, but populates it with references to the original nested child objects. Mutating nested items mutates BOTH original and copied structures!

2. Deep Copy ('copy.deepcopy(obj)'):

Recursively duplicates the container AND all nested child objects, producing a completely independent clone in memory.

Code Implementation Example

python
import copy

original = [[1, 2], [3, 4]]

# Shallow copy
shallow = copy.copy(original)
shallow[0][0] = 999
print(original[0][0]) # 999! Nested inner list was SHARED!

# Deep copy
deep = copy.deepcopy(original)
deep[1][0] = 777
print(original[1][0]) # 3! Completely independent copy!
💡Demonstrating shared nested references in shallow copy vs deepcopy isolation.
🎯 Interview Key Takeaway

Use copy.deepcopy() when cloning nested lists or dictionaries to avoid unintended shared reference mutations.

#copy#deepcopy#Shallow Copy#Deep Copy#Beginner
Back to all Python Questions→

More Python Interview Questions

Beginner LevelPython

What is the Python Global Interpreter Lock (GIL) and how does it affect multi-threading?

Beginner LevelPython

What is the difference between a List, Tuple, Set, and Dictionary in Python?

Beginner LevelPython

Why are mutable default arguments (like def func(items=[])) dangerous in Python and how do you fix them?