ProgrammingHardProduct-company MCQ pattern

What is printed?

What is printed?
fs = [lambda: i * i for i in range(4)]
gs = [lambda i=i: i * i for i in range(4)]
print([f() for f in fs], [g() for g in gs])
  1. A. [9, 9, 9, 9] [0, 1, 4, 9]
  2. B. [0, 1, 4, 9] [0, 1, 4, 9]
  3. C. [9, 9, 9, 9] [9, 9, 9, 9]
  4. D. [0, 1, 4, 9] [9, 9, 9, 9]

Correct answer: A. [9, 9, 9, 9] [0, 1, 4, 9]

Closures capture the variable, not its value (late binding): when the lambdas run, i is 3, so every call gives 9. A default argument i=i is evaluated at definition time and freezes each value.

More Python Programming questions

Exams that ask this topic