Data Structures20 min read
Data Structure Pitfalls
Avoid common mistakes: modifying lists during iteration, shallow-copy bugs, dict key errors, set ordering assumptions, and performance traps.
David Miller
September 26, 2025
8.9k209
This lesson is about mistakes that cause bugs in real projects.
1) Modifying a list while iterating
Bad:
nums = [1,2,3,4]
for n in nums:
if n % 2 == 0:
nums.remove(n)
print(nums) # can behave unexpectedly
Good:
nums = [1,2,3,4]
nums = [n for n in nums if n % 2 != 0]
print(nums)
2) Shallow copy with nested structures
a = [[1],[2]]
b = a.copy()
b[0].append(99)
print(a) # changed
Fix:
import copy
b = copy.deepcopy(a)
3) Assuming set has stable order
Sets are not designed for “index order”.
If you need order, use list.
4) KeyError in dict
Use get() for safe reads:
d = {"a": 1}
print(d.get("x", 0))
Graph: pitfalls map
flowchart TD
A[Bug] --> B[Mutation during loop]
A --> C[Shallow copy]
A --> D[Wrong structure assumption]
A --> E[Unsafe dict access]
Remember
- Use get(), copy(), deepcopy()
- Don’t mutate while iterating
- Choose structure that matches your needs
#Python#Advanced#Pitfalls