ProgrammingHardInfosys pattern
What is printed?
What is printed?
def outer():
funcs = []
x = 0
for i in range(3):
x = x + i
funcs.append(lambda: x)
return funcs
print([f() for f in outer()])- A. [0, 1, 3]
- B. [3, 3, 3]
- C. [0, 0, 0]
- D. [1, 2, 3]
Correct answer: B. [3, 3, 3]
All three lambdas close over the same local variable x. After the loop finishes, x holds its final accumulated value 0+0+1+2=3, so every call returns 3.
More Python Programming questions
- 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…
- 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))