ProgrammingHardGATE CS · Product-company placement
What is printed?
What is printed?
fs = [lambda i=i: i for i in range(3)] print([f() for f in fs])
- A. [2, 2, 2]
- B. [0, 1, 2]
- C. [0, 0, 0]
- D. TypeError
Correct answer: B. [0, 1, 2]
Giving each lambda a default argument i=i evaluates i at DEFINITION time and binds it to that lambda's own parameter, capturing the value at each iteration instead of the shared late-bound variable.
More Python Programming questions
- What is printed? python def outer(): funcs = [] x = 0 for i in range(3): x = x + i funcs.append(lambda: x) return funcs print([f() for f…
- What is printed? python adders = [] for i in range(3): def adder(x, i=i): return x + i adders.append(adder) print(adders[0](10)…
- What is printed? python x = 1 def outer2(): x = 2 def inner(): print(x) x = 3 return inner outer2()()
- What is printed? python counters = [] for i in range(3): j = i 2 counters.append(lambda: j) print([c() for c in counters])
- 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…