Python Closures Capture Variables, Not Values

🐍 Did you know that Python closures capture variables, not values? This behavior is called late binding and it can cause surprising results. Example: funcs = [] for i in range(3): funcs.append(lambda: i) # tricky line print([f() for f in funcs]) # [2, 2, 2] Why does this happen? All the lambdas keep a reference to the same variable i. When the loop finishes, i equals 2, so every function returns 2. 💡 We can fix this by forcing early binding using default arguments: funcs.append(lambda i=i: i) This creates a new local variable i for each lambda and stores the current value at definition time. #Python #Closures #ProgrammingTips #LearningInPublic #SoftwareEngineering

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories