Ch. 9 · Python

Python Shallow Copies and Nested Mutability

Python Shallow Copies and Nested Mutability. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readbeginnerupdated Oct 3, 2026

A shallow copy creates a new outer container while sharing nested references. The correct copying depth follows intended ownership.

Before you start

You should know Python functions, collections and exceptions. Use a small isolated script or interactive session to trace the example. Pay attention to when objects are created and when work executes; iteration, binding and mutation can happen at different points in a program.

The practical goal is to reason through this situation: Copying a list of dictionaries leaves each dictionary shared. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.

Step-by-step walkthrough

Step 1: Inspect nested ownership

Copying the list does not copy its dictionaries.

Step 2: Replace the changed record

Copy both the outer list and the particular dictionary being edited.

Step 3: Choose broader copying deliberately

Deep copying can be unsuitable for resources or intentionally shared references.

Worked scenario

Copying a list of dictionaries leaves each dictionary shared.

original = [{'name': 'Ada'}]
changed = list(original)
changed[0] = {**changed[0], 'name': 'Grace'}
print(original[0]['name'])  # Ada
python

Replacing a copied slot differs from mutating the shared dictionary through that slot. Nested dictionaries inside the copied record would still require further decisions.

Common mistake

Deepcopy is not always appropriate for resources or intentionally shared objects.

Verify the behavior

Mutate through a plain shallow copy, then compare with the replacement version; inspect nested references.

Interview exercise

Change one nested field independently.

Answer and reasoning

Copy the outer list and the changed dictionary, or use a suitable deep-copy policy for the complete data structure.

Continue learning

Compare the scenario with the Python interview questions and test your understanding with the Python MCQs. For terminology and implementation details, consult the reference material.

More in Python

read ✓Python · hard

Python asyncio.gather and Timeouts

Run coroutines concurrently with asyncio.gather, enforce timeouts, and handle partial failures and cancellation correctly.

~2 min readread →
read ✓Python · mid

Python Bounded Async Worker Queues

Use asyncio.Queue and a fixed worker pool to bound pending work. Trace backpressure, shutdown and failure ownership.

~3 min readread →
read ✓Python · mid

Python Asyncio and Blocking Functions

Python Asyncio and Blocking Functions. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readread →
esc