Python · The language, not just syntax

What is the difference between a shallow and a deep copy?

Mediumcopyaliasingnested dataUpdated Oct 2026
Quiz this track

Short answer

A shallow copy creates a new outer container but shares the nested objects. A deep copy recursively copies nested objects, so mutating the copy does not affect the original.

copy.copy and slicing a list produce a shallow copy. The top-level container is new, but its elements are the same objects. If those elements are mutable, changes through the copy are visible in the original.

python
import copy

original = {"tags": ["python", "api"]}
shallow = copy.copy(original)
deep = copy.deepcopy(original)

shallow["tags"].append("shallow")
print(original["tags"])  # includes shallow

deep["tags"].append("deep")
print(original["tags"])  # unchanged by deep
The shallow copy shares the inner list, so appending through it changes the original. The deep copy does not.

Practical rules

  • Immutable values do not need copying at all
  • deepcopy handles cycles with a memo dictionary and is more expensive
  • Custom classes may need __copy__ or __deepcopy__ to control semantics
  • Copying is not the same as freezing; a copy can still be mutated later

Prefer immutable data when values cross boundaries, because it removes the question of who owns a copy. When you must copy, be explicit about depth, especially for nested config, cached responses and default values.

deepcopy preserves shared references inside the copied graph by default, so two attributes pointing at the same object still point at one copied object.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1When is a shallow copy sufficient?
  2. 2How does deepcopy handle cyclic structures?
  3. 3How would you customise deepcopy for a class?
  4. 4Why can copying be a performance problem?

Say it in the interview

A shallow copy duplicates only the outer container, so nested mutable objects are shared. A deep copy recursively duplicates the graph, which is safer but more expensive and needs a memo to handle cycles. I prefer immutable data so copying is unnecessary, and when I do copy I am explicit about depth. I also implement __deepcopy__ when a class holds resources that should not be duplicated blindly.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Python mock interview and get scored feedback on depth, clarity and confidence.