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
December 21, 2025
0.0k0

This lesson is about mistakes that cause bugs in real projects. ## 1) Modifying a list while iterating Bad: ```python nums = [1,2,3,4] for n in nums: if n % 2 == 0: nums.remove(n) print(nums) # can behave unexpectedly ``` Good: ```python nums = [1,2,3,4] nums = [n for n in nums if n % 2 != 0] print(nums) ``` ## 2) Shallow copy with nested structures ```python a = [[1],[2]] b = a.copy() b[0].append(99) print(a) # changed ``` Fix: ```python 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: ```python d = {"a": 1} print(d.get("x", 0)) ``` ## Graph: pitfalls map ```mermaid 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