Shallow Copies of Containers
A shallow copy duplicates the outer container and preserves the references held in its positions or entries.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 2 min
In this article4 chapters
Track two layers
Copy [[1], [2]] with Python's list copy method. Both outer lists contain references to the same two inner lists. Replacing the first entry in the copy leaves the original outer list untouched, following the binding and mutation distinction.
Predict a nested update
Start again from that pair of outer lists. Appending 9 through the first inner list in the copy makes the original first entry appear as [1, 9] too. If a function promises isolation at both levels, copy the relevant inner lists as well and test which objects share identity.[1][2]
Trace a copy through two ordinary edits
Start with a list of two lists, [[8], [9]]. Copy the outer list to a second name and replace the first row of that copy with [4]. The original first row still contains eight because the original and copy have different outer slots. Start again and append four to the first inner list through the copy. The original first row now contains eight and four because that inner object was still shared. See mutable objects and bindings for why replacing a slot and mutating its previous value have different effects.
Copy the objects your operation can change
An operation that only moves rows around can use a shallow copy to preserve the source's row order. A program editing the values in row one also needs a defensible strategy for nested data. Sometimes it is enough to copy just the row being edited. A stable snapshot could instead extract immutable record fields. Use two rows with unequal values and a test checking the source and result after the edit. Immutable record snapshots explain why the required snapshot depth comes from later operations, not just from how the input happens to be nested.