🐍 Python Challenge: The Classic Mutable Default Argument Trap! This is perhaps one of the most infamous "gotchas" in Python Interview questions. It catches beginners and even experienced developers off guard if they aren't paying close attention to how Python handles memory. Take a look at the function definition in the image. We are calling f(1) followed immediately by f(2). What exactly will be printed to the console? 💡 The Answer & Explanation: The actual output is: ---------------- [1] [1, 2] ---------------- Why does this happen? Why isn't the second output just [2]? The secret lies in when Python evaluates default arguments. Default parameter values (like l=[ ] in the image) are evaluated only once when the function definition (def f...) is executed, not every time the function is called. Because a list ([ ]) is a mutable object, Python creates one list object in memory when the function is defined. If you don't provide a value for l, Python reuses that exact same list object for every subsequent call. 1. Call f(1): It uses the default empty list created at definition time. It appends 1. The default list object in memory is now [1]. 2. Call f(2): It uses the same default list object (which now contains [1]). It appends 2. The list becomes [1, 2]. How to fix it in real code? Use None as the default and initialize inside the function: def f(x, l=None): if l is None: l = [ ] ... Did you spot the trap immediately, or did you fall for it? Be honest in the comments! 👇 #Python #Programming #SoftwareEngineering #CodingChallenge #PythonDeveloper #TechTips #DigitalFinancialServices #BackendDevelopment
The list is created once, shared across calls. So the output will be -> [1] [1, 2]
def f(x, l=None): if l is None: l = [] l.append(x) return l print(f(1)) # Output: [1] print(f(2)) # Output: [2]