Python DP Pitfall: List Multiplication Gotcha

Python DP Pitfall Every Developer Should Know These two lines look the same… but they’re not always the same: dp = [0 for _ in range(n + 1)] dp = [0] * (n + 1) ✅ For numbers (immutable values) They behave identically. Totally safe for most dynamic programming problems. But here’s where people get burned 👇 dp = [[]] * 3 dp[0].append(1) print(dp) Output: [[1], [1], [1]] 😱 Why? Because list multiplication copies references, not objects. All elements point to the same list in memory. ✅ The correct way for mutable objects: dp = [[] for _ in range(3)] Each element is now independent. No hidden bugs. 🧠 Rule of thumb for DP in Python Storing numbers / booleans → * is fine Storing lists / dicts → always use list comprehension Small detail. Huge difference. This one has caused countless “why is my DP wrong?” moments 😅 #Python #DynamicProgramming #SoftwareEngineering #CodingTips #LeetCode #PythonGotchas

  • No alternative text description for this image

Learnt it before in a hard way this difference. Worth it though. 

Like
Reply

To view or add a comment, sign in

Explore content categories