ProgrammingHardInfosys HackWithInfy · TCS CodeVita

What is printed?

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

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

The first lambdas share the loop variable i, which equals 2 when they run. The default argument binds each value when the lambda is created, so the second list returns 0, 1, 2.

More Python Programming questions

Exams that ask this topic