Question

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

Vault Verified
Curated Intelligence
Definitive Source
Answer

A shallow copy creates a new container holding references to the same inner objects. A deep copy recursively creates new copies of everything inside. The distinction only matters when the structure contains mutable objects, which is exactly when it bites.

Copying a flat list of numbers shallowly is completely safe, because numbers are immutable and cannot be changed through either reference. Copying a list of lists shallowly gives you a new outer list whose elements are the original inner lists. Modifying an inner list through the copy changes the original, because there is only one inner list with two references to it.

That produces the classic confusing bug: you deliberately copied the data to avoid mutating the input, the copy appeared to work, and the caller sees their data change anyway.

A deep copy avoids it by duplicating every level. The cost is real: it is slower, uses proportionally more memory, and it must handle shared references and cycles, which it does by tracking objects it has already copied so a structure referencing itself does not recurse forever.

Choosing between them is a question about intent rather than safety. If you will only read the nested data, a shallow copy is cheaper and correct. If you will modify anything below the top level, you need a deep copy or you need to copy the specific parts you intend to change.

A third option is often better than either: avoid mutation entirely. Producing new values rather than modifying existing ones removes the question, and is why immutable data structures are popular in codebases where this class of bug has caused real problems.

The same distinction exists in most languages, though the syntax and defaults differ.

Related Questions