Closures and the loop variable trap

A lambda captures the variable, not the value it had at that moment. In a for loop that surprises almost everyone once.

Time O(n)Space O(n)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

A for loop has one variable i for the whole loop. All three lambdas share it, and by the time they run the loop has finished with i = 3. Declaring a variable inside the body gives each lambda its own.

Code

var actions = new List<Action>();
for (int i = 0; i < 3; i++)
    actions.Add(() => Console.Write(i));   // captures the variable i
foreach (var act in actions) act();        // prints 333

var fixedActions = new List<Action>();
for (int i = 0; i < 3; i++) {
    int copy = i;                          // a fresh variable each time
    fixedActions.Add(() => Console.Write(copy));
}
foreach (var act in fixedActions) act();   // prints 012
public class Main {
    public static void main(String[] args) {
        List<Runnable> actions = new ArrayList<>();
        int[] i = {0};                       // lambdas can only capture effectively final locals, so share a cell
        for (i[0] = 0; i[0] < 3; i[0]++)
            actions.add(() -> System.out.print(i[0]));   // captures the shared cell
        for (Runnable act : actions) act.run();          // prints 333

        List<Runnable> fixedActions = new ArrayList<>();
        for (int j = 0; j < 3; j++) {
            int copy = j;                    // a fresh variable each time
            fixedActions.add(() -> System.out.print(copy));
        }
        for (Runnable act : fixedActions) act.run();     // prints 012
    }
}
int main() {
    vector<function<void()>> actions;
    int i;
    for (i = 0; i < 3; i++)
        actions.push_back([&i] { cout << i; });   // captures the variable i by reference
    for (auto& act : actions) act();              // prints 333

    vector<function<void()>> fixedActions;
    for (int i = 0; i < 3; i++) {
        int copy = i;                             // a fresh variable each time
        fixedActions.push_back([copy] { cout << copy; });
    }
    for (auto& act : fixedActions) act();         // prints 012
}
actions = []
for i in range(3):
    actions.append(lambda: print(i, end=""))  # captures the variable i
for act in actions: act()  # prints 222 (i stops at 2 in Python)

fixed_actions = []
for i in range(3):
    def act(copy=i):  # a default value is evaluated now, once per loop
        print(copy, end="")
    fixed_actions.append(act)
for act in fixed_actions: act()  # prints 012

Tips

In the .NET library

The same rule explains why a lambda passed to Task.Run sees later changes to a captured local. Copy the value to a new local first if you need a snapshot.