Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern

Problem: Find the bug: a list of multiplier functions is built in a loop with lambdas.

Problem: Find the bug: a list of multiplier functions is built in a loop with lambdas.
fs = [lambda x: x * i for i in range(1, 4)]
gs = [lambda x, i=i: x * i for i in range(1, 4)]
print([f(10) for f in fs], [g(10) for g in gs])
What is printed?
  1. A. [30, 30, 30] [10, 20, 30]
  2. B. [30, 30, 30] [30, 30, 30]
  3. C. [0, 10, 20] [10, 20, 30]
  4. D. [10, 20, 30] [10, 20, 30]

Correct answer: A. [30, 30, 30] [10, 20, 30]

Python closures capture the variable i, not its value at creation time (late binding); after the comprehension i is 3, so every lambda in fs multiplies by 3. A default argument i=i is evaluated when each lambda is created, freezing 1, 2, 3. The same pitfall appears with callbacks created in loops.

More Coding Interview Problems questions

Exams that ask this topic