Python · Question 12 · Hard

What will be the output of the following Python code?

fs = [lambda: i for i in range(3)]
print([f() for f in fs])
  1. [0, 1, 2]
  2. [0, 0, 0]
  3. [2, 2, 2]
  4. NameError
Answer and explanation

Answer: C. [2, 2, 2]

Explanation: Each lambda looks up i when it is called, not when it is created (late binding). By then the comprehension has finished with i = 2, so all three return 2.

Previous: What will be the output of the following Python code? · Next: What will be the output of the following Python code?

Practise python

Try a fresh set of python questions with an explanation after every answer, free and without signing up: Python practice. Or sit a full placement mock test.

More python questions

More technical & programming practice

Data Structures · Algorithms · Object-Oriented Programming · DBMS · SQL · Operating Systems · Computer Networks · Software Engineering

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge