Python core · Concept
Assignment, shallow copy and deep copy
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voiceThe 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
- What does
grid = [[0] * 3] * 3followed bygrid[0][0] = 1give, and why? - How does
deepcopycope with an object that refers to itself? - Why can
deepcopyfail, or be a bad idea on every request? - How do you control copying for your own class?
The answer
What a strong answer covers
b = acopies nothing: two names, one list. A shallow copy makes a new outer list holding the same dicts, so changing a dict shows in both.deepcopycopies recursively.- Shallow copies also come from slicing (
a[:]),list(a),dict.copy()and{**d}. [[0] * 3] * 3is three references to one row, so it prints[[1, 0, 0], [1, 0, 0], [1, 0, 0]]. Fix:[[0] * 3 for _ in range(3)].deepcopykeeps 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 voicePractise 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.