What will be the output of the following Python program?

functions = [lambda: i for i in range(3)]
print([f() for f in functions])
                        

Options

  • A. [0, 1, 2]
  • B. [2, 2, 2]
  • C. [1, 2, 3]
  • D. More than one of the above
  • E. None of the above

Correct Answer (Detailed Explanation is Below)

B. [2, 2, 2]

Detailed Explanation

Python closures use late binding. All lambda functions refer to the final value of i, which is 2.