Python Default Argument Gotcha: Avoid Mutable Lists

💬 Today’s Insight: A Hidden Trap in Python (Mutable Default Arguments) Take a look at this function: def tricky(n, lst=[]): if n > 0: lst.append(n) return tricky(n-2, lst) return lst print(tricky(5)) print(tricky(4)) At first glance, everything seems normal… but the output might surprise you 👀 👉 The key issue here is using a mutable default argument ("lst=[]"). In Python, default arguments are evaluated only once when the function is defined, not each time it’s called. This means the same list is reused across multiple function calls. 📌 So what happens? - First call → builds "[5, 3, 1]" - Second call → continues using the SAME list → "[5, 3, 1, 4, 2]" 💣 This leads to unexpected behavior and bugs that are hard to trace. --- ✅ Best Practice Always use "None" as the default value for mutable types: def tricky(n, lst=None): if lst is None: lst = [] if n > 0: lst.append(n) return tricky(n-2, lst) return lst Now each function call gets its own fresh list ✔️ --- 🎯 Takeaway - Avoid using mutable objects as default arguments - Use "None" and initialize inside the function - Small detail… but huge impact on your code quality --- #Python #Programming #DataScience #AI #CodingTips #SoftwareEngineering #LearningJourney

To view or add a comment, sign in

Explore content categories