ProgrammingVery hardInfosys · Python · Advanced

What is printed?

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

Correct answer: A. [0, 2, 4] [4, 4, 4]

The default argument i=i freezes each loop value; the plain lambdas look up i when called, after the loop ended with i = 2.

More Python Programming questions

Exams that ask this topic