Python Tutorial
Python Copy Lists
list2 = list1 copies the reference, not the data. Use copy(), list(), or a slice to get a real copy.
Wrong Copy
Both names point to the same list. Changing one changes the other.
thislist = ["apple", "banana", "cherry"]
list2 = thislist
list2.append("orange")
print(thislist)copy(), list(), slice
Three ways to duplicate the items.
thislist = ["apple", "banana", "cherry"]
print(thislist.copy())
print(list(thislist))
print(thislist[:])📘 Real-World Deep Dive
Most list "copies" are shallow and that's a frequent source of subtle bugs. Knowing when you need <code>list.copy</code>, <code>list(xs)</code>, slicing, and <code>copy.deepcopy</code> is the difference between correct code and silent aliasing.
Real-Life Scenario
Defensive deep-copy before a destructive operation; show what goes wrong with shallow copy on a list of dicts.
Real-Life Example
import copy
shared = [{"k": "v"}, {"k": "w"}]
shallow = shared.copy() # shares inner dicts
deep = copy.deepcopy(shared)
print("shallow is shared:", shallow is shared)
print("shallow[0] is shared[0]:", shallow[0] is shared[0])
print("deep[0] is shared[0]:", deep[0] is shared[0])
shared[0]["k"] = "MUTATED"
print("after mutation:")
print(" shared :", shared)
print(" shallow :", shallow) # inner dict mutated!
print(" deep :", deep) # unchangedExpected Output
shallow is shared: False
shallow[0] is shared[0]: True
deep[0] is shared[0]: False
after mutation:
shared : [{'k': 'MUTATED'}, {'k': 'w'}]
shallow : [{'k': 'MUTATED'}, {'k': 'w'}]
deep : [{'k': 'v'}, {'k': 'w'}]Common mistakes
new = old_listaliases;new = list(old)andnew = old[:]do shallow copies.- Mutable inner objects mean shallow copy doesn't isolate you from mutations.
deepcopycan recurse through arbitrary graphs; cap withdepthor memo for big structures.
🚀 Performance & Best Practices
list.copy()is faster thancopy.copy(list);list(xs)is competitive.- For lists of primitives, slice (
xs[:]) andlist(xs)are equally fast — pick the readable form. - Use
copy.replace(Python 3.13+) on dataclasses instead of deepcopy.
🧪 Try It Yourself
- Implement
shallow_replace(items, predicate, replacement)that returns a brand-new outer list. - Profile
deepcopyvs. JSON-roundtrip (json.loads(json.dumps(x))) for nested data. - Write a recursive
deep_freezethat converts dicts/lists into tuples inside tuples.