Skip to the solution
MediumDSA11 min read

What is the difference between shallow and deep copy?

1.2k views

The problem

Question presented to candidate: "If I have a list of lists and I write b = a, b = a[:] or b = copy.deepcopy(a), what is different about b in each case? When does a shallow copy bite you, and why not just deep-copy everything?"

What a strong answer should cover:

  • Assignment binds a second name to the same object; nothing is copied (b is a is True)
  • A shallow copy (copy.copy, list(x), x[:], x.copy(), dict(x), {**d}) builds a new outer container whose slots point at the same inner objects
  • A deep copy (copy.deepcopy) recursively copies everything reachable, using a memo dict so shared references stay shared and cycles do not loop forever
  • Consequence: mutating a nested object leaks through a shallow copy, but rebinding a top-level slot does not
  • Costs and limits: deep copy is slower and uses more memory; immutable objects (tuples of immutables, ints, strings) come back as the same object; functions and classes are not duplicated; modules, locks and sockets cannot be copied; __copy__ / __deepcopy__(memo) customise it
  • Bonus: copy.replace() (Python 3.13) for a modified shallow copy, and the [[]] * 3 trap

Clarifying questions expected:

  • Is the structure nested, and does it contain mutable objects or resources (files, connections, locks)?
  • Does the copy need to be independent, or is sharing the inner objects acceptable (or even desired)?

Code / implementation expected: Optional β€” a nested list showing a shallow copy leaking a nested mutation and a deep copy staying independent.

  • shallow-deep-copy

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

11 min read Β· 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonAssignment vs shallow vs deep copy on a nested list
Pythondeepcopy internals: shared references, cycles, custom hooks, what cannot be copied
PythonPython 3.13 copy.replace(): a modified shallow copy
# Python 3.13+: copy.replace() makes a modified shallow copy
import copy
import sys
from dataclasses import dataclass, field
from datetime import date
from typing import NamedTuple

print(sys.version_info[:2] >= (3, 13))

@dataclass(frozen=True)
class Order:
    id: int
    status: str
    lines: list = field(default_factory=list)

o1 = Order(1, "new", ["pen"])
o2 = copy.replace(o1, status="paid")
print(o2)
# replace is SHALLOW: the list is shared
print(o2.lines is o1.lines)

class Point(NamedTuple):
    x: int
    y: int

print(copy.replace(Point(1, 2), y=5))
print(copy.replace(date(2026, 1, 31), day=1))

# A plain class does not support it
class Plain:
    pass
try:
    copy.replace(Plain())
except TypeError as e:
    print("TypeError:", e)

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 35 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

What is a race condition and how do locks prevent it?

Continue