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
import copy
original = {"name": "Ada", "skills": ["python", "sql"]}
alias = original # same objectshallow = original.copy() # new dict, same 'skills' listdeep = copy.deepcopy(original) # new dict, new list
original["skills"].append("go")
alias["skills"] # ['python', 'sql', 'go']shallow["skills"] # ['python', 'sql', 'go'] — shared inner listdeep["skills"] # ['python', 'sql'] — independent| Operation | New outer object? | New nested objects? |
|---|---|---|
b = a | No | No |
| Shallow copy | Yes | No |
| Deep copy | Yes | Yes |
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?
nums = [1, 2, 3]a = nums.copy() # shallowb = nums[:] # shallowc = list(nums) # shallowd = copy.deepcopy(nested_structure)The grid bug: [[0] * 3] * 3
grid = [[0] * 3] * 3grid[0][0] = 1print(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:
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?
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"] — shareddeep.skills; // ["js"]deep.joined instanceof Date; // truestructuredClone 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:
| Value | After the JSON round trip |
|---|---|
Date | an ISO string |
undefined property | removed |
Map / Set | {} |
NaN, Infinity | null |
| Circular reference | throws 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:
List<String> copy = new ArrayList<>(original); // shallow, mutableList<String> frozen = List.copyOf(original); // shallow, immutablePerson p2 = new Person(p1); // copy constructor you writeObject.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
- Believing slicing makes an independent copy of nested data.
rows[:]copies the outer list only. - Mutable default arguments in Python.
def add(item, items=[])shares one list across every call. Useitems=Noneand create the list inside. - Copying too late. By the time you copy, the shared object may already have been modified.
- 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.