Data Structures & AlgorithmsHardGoogle · Flipkart interview

Edge case: lambdas created in a loop (closures).

Edge case: lambdas created in a loop (closures).
fs = [lambda: i * 10 for i in range(3)]
gs = [lambda i=i: i * 10 for i in range(3)]
print([f() for f in fs], [g() for g in gs])
What is printed?
  1. A. [0, 10, 20] [0, 10, 20]
  2. B. [20, 20, 20] [0, 10, 20]
  3. C. [20, 20, 20] [20, 20, 20]
  4. D. [0, 10, 20] [20, 20, 20]

Correct answer: B. [20, 20, 20] [0, 10, 20]

Closures capture the VARIABLE i, not its value, and look it up when called, after the comprehension finished with i = 2: [20, 20, 20]. A default argument is evaluated at definition time, freezing each value: [0, 10, 20].

More Coding Interview Problems questions

Exams that ask this topic