Bug Fix

The Lazy Lambda

The Lazy Lambda

Bug Report

A list of lambda functions is created in a loop, each one meant to return its own loop index (0, 1, 2). But when called, every single one returns 2.

ClosuresLoopsLate Binding
Fix the Bug: The Lazy Lambda

Python closures capture variables by reference, not by value, and lambdas don't evaluate the variable until they are CALLED (late binding). By the time all the lambdas run, the loop has already finished, so they all see the loop variable's final value.

EditorPython · JSX
PreviewUpdates on Run Tests
Loading preview…
Tests
Should bind 'i' as a default argument inside the lambda
Should keep the loop structure using range(3)
Should NOT leave the lambda capturing 'i' without a default