ProgrammingHardGATE CS · Product-company placement

What is printed?

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

Correct answer: B. [0, 1, 2]

Giving each lambda a default argument i=i evaluates i at DEFINITION time and binds it to that lambda's own parameter, capturing the value at each iteration instead of the shared late-bound variable.

More Python Programming questions

Exams that ask this topic