"Python Shallow vs Deep Copy: Choose Right, Avoid Bugs"
"Python shallow vs deep copy is the difference between cloning a suitcase and cloning the clothes inside it. See both fail and succeed on nested configs, compare them head-to-head, and learn when deepcopy is overkill — plus how to customize copying for your own classes."
Last updated: 2026-10-05 Get this decision right and an entire class of bugs — mutations teleporting between "independent" objects — disappears from your codebase. Get it wrong and you'll spend an afternoon staring at a dict that changes itself. This is a verdict-driven comparison of Python shallow vs deep copy: what each one actually clones, where each one breaks, and exactly which to reach for in each scenario. The choice, stated plainly You have a nested structure — say, an API payload or a job config — and you need a copy you can mutate safely. Three levels of cloning exist: Assignment ( b = a ): no copy at all. Two names, one object. Shallow copy ( copy.copy(a) , a.copy() , a[:] ): new outer container, but the nested objects inside are *shared references*. Deep copy ( copy.deepcopy(a) ): new outer container *and* recursively new nested objects. Full isolation. Level 1 surprises people first, so let's get it out of the way: original = [1, [2, 3]] alias = original # NOT a copy — same object alias[1].append(99) print(original) # [1, [2, 3, 99]] — original changed too print(alias is original) # True Watch the wrong choice corrupt data in three lines: payload = {"user": {"name": "ann", "tags": ["admin"]}, "page": 1} shallow = payload.copy() shallow["user"]["tags"].append("banned") print(payload["user"]["tags"]) # ['admin', 'banned'] — the ORIGINAL changed! payload["page"] = 99 print(shallow["page"]) # 1 — top level IS independent The shallow copy cloned the outer dict, but shallow["user"] and payload["user"] are the *same inner dict*. That's the whole game: shallow copies the suitcase, not the clothes. Option A — shallow copy: fast, cheap, one level deep copy.copy() (or the built-in .copy() methods and slicing) duplicates the top-level…