Part 04 / Topic 6 of 11
Mutability and copying
- Mutable (can change):
list,dict,set. - Immutable (cannot change):
int,float,str,tuple,bool.
b = a does not copy. Both names point to the same object (aliasing). It is like two people sharing one Google Doc: a change by one is seen by both.
.copy() makes a shallow copy: a new outer object, but inner lists are still shared.
copy.deepcopy() copies everything, inner objects too. It lives in the copy module, so you need import copy first (imports are covered in Part 7).
Real-world example: copying a meal plan.
import copy # (imports are covered in Part 7)
plan = ["idli", "dosa"]
alias = plan # same list, two names
alias.append("poha")
print(plan) # ['idli', 'dosa', 'poha']
backup = plan.copy() # new list
backup.append("upma")
print(plan) # ['idli', 'dosa', 'poha']
print(backup) # ['idli', 'dosa', 'poha', 'upma']
week = [["idli", "dosa"], ["poha"]]
shallow = week.copy()
deep = copy.deepcopy(week)
week[0].append("vada") # change an INNER list
print(shallow[0]) # ['idli', 'dosa', 'vada'] (shared!)
print(deep[0]) # ['idli', 'dosa'] (safe)
| Way | New outer object? | New inner objects? |
|---|---|---|
b = a |
❌ | ❌ |
a.copy(), a[:], list(a) |
✅ | ❌ |
copy.deepcopy(a) |
✅ | ✅ |
🔍 Going deeper: use
isto check if two names share one object (alias is plan→True). For a flat list of numbers or strings, a shallow copy is enough because those items are immutable.deepcopyis slower, so use it only for nested data you plan to change.
Done here? The practice set for Part 4 — 8 exercises with solutions — is on the part page.