Skip to the page

Python core · Concept

Assignment, shallow copy and deep copy

The interviewer asks

For a list of dictionaries, what's the difference between b = a, copy.copy(a) and copy.deepcopy(a)? Which would you use, and when?

Then

Follow-ups the interviewer asks next

  1. What does grid = [[0] * 3] * 3 followed by grid[0][0] = 1 give, and why?
  2. How does deepcopy cope with an object that refers to itself?
  3. Why can deepcopy fail, or be a bad idea on every request?
  4. How do you control copying for your own class?

The answer

What a strong answer covers

  • b = a copies nothing: two names, one list. A shallow copy makes a new outer list holding the same dicts, so changing a dict shows in both. deepcopy copies recursively.
  • Shallow copies also come from slicing (a[:]), list(a), dict.copy() and {**d}.
  • [[0] * 3] * 3 is three references to one row, so it prints [[1, 0, 0], [1, 0, 0], [1, 0, 0]]. Fix: [[0] * 3 for _ in range(3)].
  • deepcopy keeps a memo dict, so cycles and shared objects are copied once.
  • It can fail on objects such as locks and sockets (TypeError: cannot pickle '_thread.lock' object) and is slow on big structures, because it walks every object in Python.
  • Custom control: __copy__ and __deepcopy__; copy.replace() (3.13) for a changed copy of a dataclass or named tuple.
  • Often better: immutable data that needs no copy.

The red pen

Common traps

Avoid:calling slicing a deep copy; using deepcopy everywhere "to be safe".

Practise this out loud

Say your answer out loud to an AI interviewer that follows up, and get a score for it.

Practise by voice

Practise questions like this out loud

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview