ProgrammingHardAccenture pattern
What is printed?
What is printed?
def makeFuncs():
return [lambda x, n=n: x ** n for n in range(1, 4)]
fns = makeFuncs()
print([f(2) for f in fns])- A. [8, 8, 8]
- B. [2, 4, 8]
- C. [1, 2, 3]
- D. [2, 2, 2]
Correct answer: B. [2, 4, 8]
The default argument n=n captures the current loop value at DEFINITION time for each lambda, avoiding the late-binding trap. So the three lambdas compute 2**1, 2**2, 2**3 = 2, 4, 8.
More Python Programming questions
- What is printed? python def f(n): if n == 0: return 0 return 1 + f(n - 1) print(f(100))
- What is printed? python d = {} d.setdefault("a", []).append(1) d.setdefault("a", []).append(2) d.setdefault("b", []).append(3) print(d)
- What is printed? python class A: def len(self): return 0 a = A() print(bool(a)) if a: print("truthy") else: print("falsy")
- What is printed? python x = 10 class C: x = 20 def m(self): return x c = C() print(c.m(), C.x)
- What is printed? python def f(x, y=10): def g(): return x + y y = 20 return g() print(f(1))
- What is printed? python nums = [1, 2, 3] doubled = list(map(lambda x: x 2, nums)) evens = list(filter(lambda x: x % 2 == 0, nums))…