ProgrammingHardProduct-company MCQ pattern
What is printed?
What is printed?
counters = []
for i in range(3):
j = i * 2
counters.append(lambda: j)
print([c() for c in counters])- A. [0, 2, 4]
- B. [4, 4, 4]
- C. [0, 0, 0]
- D. [2, 2, 2]
Correct answer: B. [4, 4, 4]
Every lambda closes over the same variable j, which keeps being reassigned each iteration (0, 2, 4). After the loop ends, j holds its last value, 4, so all three closures return 4.
More Python Programming questions
- What is printed? python def deco2(f): print("decorating", f.name) def wrapper(a, kw): return f(a, kw) return wrapper @deco2 def foo()…
- What is printed? python counter = 0 def countcalls(f): def wrapper(a, kw): global counter counter += 1 return f(a, kw) return wrapper…
- What is printed? python def applytwice(f): def wrapper(x): return f(f(x)) return wrapper @applytwice def inc(x): return x + 1 print(inc(5))
- What is printed? python def outerdeco(f): print("setup") def wrapper(a, kw): print("call") return f(a, kw) return wrapper @outerdeco def…
- What is printed? python def h(a, b, c): return a + b + c args = [1, 2, 3] print(h(args)) args2 = [1, 2] try: print(h(args2)) except…
- What is printed? python def k(a, , b): return a + b try: k(1, 2) except TypeError: print("TypeError") print(k(1, b=2))