Python Lambda Closures: Understanding Late Binding

Today I explored a very interesting Python behavior while working with lambdas inside a list comprehension: funcs = [lambda x: x * i for i in range(3)] print(funcs[1](2)) At first glance, you might expect each lambda to capture its own value of "i" (0, 1, 2). But the output is: 4 Why? Because of something called "Late Binding". In Python, closures capture variables by reference, not by value. This means all the lambdas refer to the same variable "i", and by the time we call them, the loop has finished and "i" equals 2. So effectively, all functions behave like: lambda x: x * 2 That’s why even if we call all of them with "x = 3", we get: [6, 6, 6] ✅ The Fix? We can bind the current value of "i" at definition time using a default argument: funcs = [lambda x, i=i: x * i for i in range(3)] Now each lambda keeps its own copy of "i", and the output becomes: [0, 3, 6] This small example is a powerful reminder that understanding how Python handles scope and closures is essential for writing clean and predictable code. #Python #Closures #Lambda #ProblemSolving #100DaysOfCode #AI #MachineLearning #InstantAcademy

To view or add a comment, sign in

Explore content categories