SoftwareSideHustles
Concepts

Deep Copy vs Shallow Copy: Why Changing the Copy Changed the Original

Why editing a "copy" of a list or object also changes the original, the difference between assignment, shallow copy and deep copy, and how to copy correctly in Python, JavaScript and Java.

By Software Side Hustles Editorial Team · Published · Updated · 5 min read

Quick answer: assignment (b = a) copies a reference, so both names point at the same object. A shallow copy creates a new outer container but shares the items inside it. A deep copy recursively copies everything. If your data contains nested lists, dictionaries or objects and you need an independent copy, use copy.deepcopy(x) in Python or structuredClone(x) in JavaScript.

Assignment, shallow copy and deep copy

python
import copy
original = {"name": "Ada", "skills": ["python", "sql"]}
alias = original # same object
shallow = original.copy() # new dict, same 'skills' list
deep = copy.deepcopy(original) # new dict, new list
original["skills"].append("go")
alias["skills"] # ['python', 'sql', 'go']
shallow["skills"] # ['python', 'sql', 'go'] — shared inner list
deep["skills"] # ['python', 'sql'] — independent
OperationNew outer object?New nested objects?
b = aNoNo
Shallow copyYesNo
Deep copyYesYes

For flat data — a list of numbers or strings — a shallow copy is enough, because numbers and strings are immutable and cannot be changed through the copy.

How do I copy a list or dictionary in Python?

python
nums = [1, 2, 3]
a = nums.copy() # shallow
b = nums[:] # shallow
c = list(nums) # shallow
d = copy.deepcopy(nested_structure)

The grid bug: [[0] * 3] * 3

python
grid = [[0] * 3] * 3
grid[0][0] = 1
print(grid) # [[1, 0, 0], [1, 0, 0], [1, 0, 0]]

Multiplying the outer list repeats a reference to the same inner list three times. Change one row and every row changes. Build independent rows with a comprehension:

python
grid = [[0] * 3 for _ in range(3)]

The inner [0] * 3 is fine, because integers are immutable.

How do I deep copy an object in JavaScript?

javascript
const original = { name: "Ada", skills: ["js"], joined: new Date("2020-01-01") };
const shallow = { ...original }; // or Object.assign({}, original)
const deep = structuredClone(original); // modern browsers and Node.js 17+
shallow.skills.push("go");
original.skills; // ["js", "go"] — shared
deep.skills; // ["js"]
deep.joined instanceof Date; // true

structuredClone handles nested objects, arrays, Date, Map, Set and even circular references. It cannot clone functions (it throws a DataCloneError), DOM nodes, or class behaviour — a cloned class instance becomes a plain object without its methods.

The older JSON.parse(JSON.stringify(obj)) trick is lossy:

ValueAfter the JSON round trip
Datean ISO string
undefined propertyremoved
Map / Set{}
NaN, Infinitynull
Circular referencethrows TypeError

Use it only when you know the data is plain JSON.

Copying arrays in JavaScript

[...arr], arr.slice() and Array.from(arr) are shallow. An array of objects copied with spread still shares the objects; changing copy[0].name changes arr[0].name. Map to new objects if you need to change them: arr.map((o) => ({ ...o })).

How do I copy objects in Java?

Java has no built-in deep copy. The usual options are:

java
List<String> copy = new ArrayList<>(original); // shallow, mutable
List<String> frozen = List.copyOf(original); // shallow, immutable
Person p2 = new Person(p1); // copy constructor you write

Object.clone() is shallow by default and awkward to implement correctly; Effective Java recommends copy constructors or static factory methods instead. For deep copies of complex graphs, write the copying explicitly, or serialise and deserialise (for example with Jackson) if performance is not critical.

The more idiomatic Java answer is often immutability: records with immutable fields and List.copyOf can be shared freely because nobody can change them.

When should you copy at all?

Copying is a defensive tool. You need it when:

  • A function must not modify its input. Sorting a list passed in by the caller with list.sort() mutates their data; sorted(list) does not. See pass by value vs pass by reference.
  • State management requires new objects. React and Redux detect changes by reference, so you must create new objects rather than mutate existing ones. A shallow copy at each changed level is the norm: { ...state, user: { ...state.user, name } }.
  • You store something a caller can still change. A class that keeps a reference to a list passed into its constructor can have its internals modified from outside. Copy on the way in (and out).

Deep copies have a cost: they allocate and traverse everything. For large structures, prefer designs where data is not mutated after creation, so copies are unnecessary.

Common mistakes

  1. Believing slicing makes an independent copy of nested data. rows[:] copies the outer list only.
  2. Mutable default arguments in Python. def add(item, items=[]) shares one list across every call. Use items=None and create the list inside.
  3. Copying too late. By the time you copy, the shared object may already have been modified.
  4. Deep-copying objects that hold resources — database connections, file handles, locks. Those should be shared, not copied.

Frequently asked questions

Is list.copy() a deep copy?

No. It is shallow: the new list contains the same element objects.

Is the spread operator a deep copy?

No. { ...obj } and [...arr] copy one level only.

What is the fastest way to deep copy in JavaScript?

structuredClone is the standard, correct choice. Hand-written copy functions for a known shape can be faster, but measure before optimising.

Why does copy.deepcopy not copy my class correctly?

It does by default, attribute by attribute. If your class holds resources or caches, implement __deepcopy__ to control what is shared.

Where this skill pays off

"The function must not modify its input" is a requirement that AI-generated code breaks surprisingly often — our free guide on how to evaluate AI-generated code walks through exactly that bug. Catching it, and explaining it in one clear sentence, is what AI code-evaluation work pays for.

Cookies on this site

We use essential cookies to run the questionnaire, practice labs and sign-in. With your permission we'd also like to use analytics to understand which pages help people, and advertising cookies to measure our Google Ads. Rejecting never limits any feature. Cookie policy