ProgrammingHardIBM · Deloitte pattern
What is printed?
What is printed?
def outer():
x = []
def appendVal(v):
x.append(v)
return x
return appendVal
f1 = outer()
f2 = outer()
print(f1(1), f1(2), f2(3))- A. [1, 2] [1, 2] [1, 2, 3]
- B. [1] [1, 2] [3]
- C. [1, 2] [1, 2] [3]
- D. [1, 2, 3] [1, 2, 3] [1, 2, 3]
Correct answer: C. [1, 2] [1, 2] [3]
Each call to outer() creates its OWN fresh list x. f1 and f2 are closures over two separate lists, so f1's calls share and grow one list ([1], then [1,2]), while f2's call starts its own fresh list ([3]).
More Python Programming questions
- What is printed? python def validate(f): def wrapper(x): if x < 0: raise ValueError("negative") return f(x) return wrapper @validate def…
- What is printed? python def makeFuncs(): return [lambda x, n=n: x n for n in range(1, 4)] fns = makeFuncs() print([f(2) for f in fns])
- 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)