How to create a lambda inside a Python loop?

Creating lambda functions inside Python loops requires careful handling to avoid common pitfalls. The key issue is that lambdas created in loops can capture variables by reference, leading to unexpected behavior.

Using a Helper Function

The most straightforward approach is to use a helper function that returns a lambda ?

def square(x): 
    return lambda: x*x

list_of_lambdas = [square(i) for i in [1, 2, 3, 4, 5]]
for f in list_of_lambdas: 
    print(f())
1
4
9
16
25

Using Default Parameters

You can capture the loop variable using default parameters in the lambda ?

list_of_lambdas = [lambda i=i: i*i for i in range(1, 6)]
for f in list_of_lambdas:
    print(f())
1
4
9
16
25

Why Default Parameters Work

Without default parameters, all lambdas would reference the same variable ?

# This creates a common pitfall
list_of_lambdas = []
for i in range(1, 6):
    list_of_lambdas.append(lambda: i*i)

# All lambdas use the final value of i
for f in list_of_lambdas:
    print(f())
25
25
25
25
25

Comparison

Method Syntax Best For
Helper Function def helper(x): return lambda: x*x Complex logic, reusability
Default Parameters lambda i=i: i*i Simple operations, list comprehensions
Regular Loop for i in range(): append(lambda: i*i) Avoid - causes reference issues

Conclusion

Use default parameters lambda i=i: i*i for simple cases or helper functions for complex logic. Avoid creating lambdas directly in regular loops without proper variable capture.

Updated on: 2026-03-24T20:37:53+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements