ProgrammingHardProduct-company MCQ pattern
What is printed?
What is printed?
fs = [lambda: i for i in range(3)] print([f() for f in fs])
- A. NameError
- B. [0, 1, 2]
- C. [2, 2, 2]
- D. [0, 0, 0]
Correct answer: C. [2, 2, 2]
Closures bind late: each lambda looks up i when it is CALLED, and by then the comprehension has finished with i = 2. Writing lambda i=i: i fixes the value at creation time.
More Python Programming questions
- What is printed? python def f(x, lst=[]): lst.append(x) return lst a = f(1) b = f(2, []) c = f(3) print(a, b, c)
- What is printed? python def f(): try: return 1 finally: return 2 print(f())
- What is printed? python print(1 < 2 > 1.5, 3 > 2 == 2, (3 > 2) == 2)
- What is printed? python a = [1, 2, 3] b = a a = a + [4] b += [5] print(a, b)
- What is printed? python print(-2 2, (-2) 2, 2 -1)
- What is printed? python print(0 or [] or "x", 1 and 0 and 5, None or 0)