What is the output of the following Python code? funcs = ; print()
Correct answer C. [2, 2, 2]
Explanation
Closures capture variables, not values, and look them up when called. All three lambdas refer to the same comprehension variable i, which is 2 once the loop has finished, so each returns 2. Binding the current value with a default argument, as in lambda i=i: i, gives [0, 1, 2].
Answer checked How we write and check questions
Discussion