Python Bug Hunt Hard +35 XP
Scope Error in Loop
This should create 3 functions that print 0, 1, 2 but all print 2.
PythonFind the bug
1
functions = []2
for i in range(3):3
functions.append(lambda: print(i))4
5
for f in functions:6
f() The bug is on line 3
Select the correct fix
Show answer and explanation
Answer: lambda i=i: print(i)
Lambda captures the variable i by reference, not value. Using default argument i=i captures the current value.
Hint: Closures capture variables, not values.
What this challenge tests
Bug Hunt in Python: closures, lambda, scope.