Deep Copy vs Shallow Copy in Python
In this lesson: Difference between shallow and deep copy in Python — copy(), deepcopy(), nested lists — with output and diagrams. In Hindi & English.
Why copying matters
In Python, copying data is trickier than it looks. If you copy the wrong way, changing the copy can secretly change the original. Understanding shallow copy and deep copy helps you avoid these confusing bugs, especially with nested data like lists inside lists.
Assignment is not a copy
a = [1, 2, 3]
b = a # NOT a copy — same list
b.append(4)
print(a) # a changed too!
b = a just gives the same list a second name. Changing b also changes a, because they point to one object. This surprises many beginners.
Shallow copy
a = [[1, 2], [3, 4]]
b = a.copy() # shallow copy
b[0].append(99) # change a nested list
print(a) # nested change leaked!
A shallow copy makes a new outer list, but the inner lists are still shared. So changing a nested list in b also affects a. Fine for flat lists, risky for nested ones.
Deep copy
import copy
a = [[1, 2], [3, 4]]
b = copy.deepcopy(a) # fully independent copy
b[0].append(99)
print(a) # original unchanged
copy.deepcopy copies every level, including the inner lists. Now b is completely separate — changing its nested data leaves a untouched.
When to use which
- Flat list of numbers/strings → a shallow copy (
.copy(),a[:]) is enough. - Nested data (lists of lists, dicts of lists) that you will edit → use
copy.deepcopy. - Just another name, changes should be shared → plain assignment
b = a.
Choose based on whether the inner objects should be shared or independent.
Common mistakes
- Thinking
b = acopies. It only makes another name for the same object. - Using a shallow copy for nested data. Inner changes leak — use deepcopy.
- Forgetting to import copy.
deepcopyneedsimport copyfirst. - Deep copying huge data needlessly. It is slower — only deepcopy when you truly need independence.
Summary
b = ais not a copy — it is another name for the same object.- A shallow copy copies the outer object but shares nested objects.
- A deep copy (
copy.deepcopy) copies every level independently. - Use shallow for flat data, deep for nested data you will edit.
- Deep copy is safer but slower — use it only when needed.
Next, review data structures in list, tuple, set and dict, or explore list comprehension.
Frequently Asked Questions
What is the difference between deep copy and shallow copy?
Why is assignment not a copy in Python?
b = a does not copy — it makes b another name for the same object. Changing b also changes a. To get a real copy you must use slicing, .copy(), or the copy module.How do I make a shallow copy?
list.copy(), list(a), a[:], or copy.copy(a). These copy the top level, but any nested lists are still shared between the original and the copy.How do I make a deep copy?
copy.deepcopy(a). It recursively copies every level, so changing a nested item in the copy does not affect the original at all.