QamoosTech
Programming FundamentalsData structuresIntermediatePythonJavaScript

Shallow vs Deep Copy

PronunciationSHAL-oh vee-ess DEEP KOP-ee

Definition

A shallow copy duplicates only the outer container, so nested objects are still shared. A deep copy duplicates everything inside it too.

Where you hear it

In Python and JavaScript debugging, interviews, and when changing a copied list unexpectedly changes the original.

Examples

  • A shallow copy of the list still shares the inner dictionaries with the original.
  • Use a deep copy when the structure contains nested lists.
  • A deep copy of the cart lets us change the copy's items without touching the original.

Common mistake

Assuming list.copy() or [:] is fully independent. It copies one level only.

Don't confuse with

Aliasing, where there is no copy at all: two names for one object.

Say it at work

  • In a meeting or chatIt's a shallow copy, so the inner lists are still shared.
  • In an email or ticketDeep-copy the config before each test so they don't affect each other.