ProgrammingHardGATE CS · Product-company placement
What is printed?
What is printed?
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
r = f(1)
print(f(2, r), f(3), r)- A. [1, 2] [1, 2, 3] [1, 2, 3]
- B. [2] [3] [1]
- C. [1, 2] [3] [1, 2]
- D. [1, 2] [3] [1]
Correct answer: C. [1, 2] [3] [1, 2]
The None sentinel gives every default call a fresh list, so f(3) returns [3]. f(2, r) appends to the list r refers to, so r prints [1, 2].
More Python Programming questions
- What is printed? python class Cart: def init(self, items=[]): self.items = items a = Cart(); b = Cart(); c = Cart([])…
- What is printed? python fs = [] for i in range(3): fs.append(lambda x: x + i) i = 10 print([f(1) for f in fs])
- What is printed? python def make(): fs = [] for i in range(3): fs.append(lambda: i) i = "z" return fs print([f() for f in make()])
- What is printed? python from functools import partial def p(a, b): return a 10 + b fs = [partial(p, i) for i in range(3)] gs = [lambda b…
- What is printed? python def counter(): count = 0 def inc(): nonlocal count count += 1 return count def peek(): return count return inc…
- What is printed? python x = 0 def outer(): x = 1 def mid(): def inner(): nonlocal x x += 10 return x return inner() r = mid() return r, x…