Copy vs deepcopy
A shallow copy duplicates a container but reuses the element objects. A deep copy walks the graph and clones everything. Assignment (b = a) copies no objects at all.
Detailed Explanation
b = a binds a second name. b = a.copy() or b = a[:] or b = list(a) or copy.copy(a) builds a new container. The new list has its own slots. Those slots still point at the same inner objects. If the inner objects are mutable, b[0]["qty"] = 2 changes a[0]["qty"].
copy.deepcopy(a) builds a new container and recursively copies each child, using a memo dict so a cycle does not recurse forever. The result is an independent graph. It is also slower and can copy too much: a deepcopy of an object that holds a logger, a socket, or a module-level registry is a bug, not a feature.
Custom classes control copying with __copy__ and __deepcopy__. Dataclasses can be copied with dataclasses.replace for a shallow field-wise new instance. copy.copy on an instance without __copy__ copies the instance's __dict__ (or slots) shallowly.
Slices and constructors are shallow. dict.copy(), set.copy(), list.copy() are shallow. list(nested) is shallow. There is no list.deepcopy; use copy.deepcopy.
Pickle and json round-trips are accidental deep copies with extra constraints (the graph must be serialisable). Prefer copy when you mean copy.
When you only need to protect one level (a list of ints), shallow is enough because ints are immutable. When you have a list of dicts, shallow is the bug you will spend an afternoon on. Draw the boxes: names, containers, leaves.
Code Examples
import copy
rows = [{"sku": "A-1", "qty": 1}]
shallow = copy.copy(rows)
deep = copy.deepcopy(rows)
shallow[0]["qty"] = 9
print(rows[0]["qty"]) # 9, inner dict was shared
print(deep[0]["qty"]) # 1# Assignment is not a copy.
left = [1, 2]
right = left
right.append(3)
print(left) # [1, 2, 3]# Immutable elements make a shallow copy enough.
nums = [1, 2, 3]
other = nums[:]
other[0] = 9
print(nums, other) # [1, 2, 3] [9, 2, 3]Common Gotchas
`copy.copy` on a list of dicts
the dicts are aliases. Use `deepcopy` or copy each row.
Deepcopying a live object graph
threads, sockets, and module globals should not be cloned. Write `__deepcopy__` that reuses them, or do not deepcopy.
`dict.copy` is shallow
nested dicts stay shared.