Question discussion

What is the output of the following Python code?fs = [lambda: i for i in range(3)] print([f() for f in fs])

918Medium DSSSB TGT Computer Science 0 replies

What is the output of the following Python code?

fs = [lambda: i for i in range(3)]
print([f() for f in fs])
  • A[0, 1, 2]
  • B[3, 3, 3]
  • C[2, 2, 2]
  • D[0, 0, 0]
Correct answer: C

Explanation

The lambdas look up i when called (late binding); after the loop i is 2, so every call returns 2.

Discussion 0

Nobody has replied yet. Start the discussion!