ProgrammingModerateTCS NQT · Python
What is printed?
What is printed?
def f(x, acc=[]):
acc.append(x)
return len(acc)
print(f(1), f(2), f(3, []), f(4))- A. 1 1 1 1
- B. 1 2 1 1
- C. 1 2 1 3
- D. 1 2 3 4
Correct answer: C. 1 2 1 3
The default list is created once and shared: calls 1, 2 and 4 grow it to length 1, 2, 3; the explicit [] in f(3, []) gives a fresh list of length 1.
More Python Programming questions
- What is printed? python print(all([]), any([]), all([0]), any([[]]), any([[0]]))
- What is printed? python w = ['pear', 'fig', 'apple', 'kiwi', 'date'] print(sorted(w, key=len), sorted(w, key=len, reverse=True))
- What is printed? python print(7 // 2, -7 // 2, 7 % -3, divmod(-7, 2), 2 -1)
- What is printed? python print({x % 3 for x in range(10)}, {x: x x for x in range(3)})
- What is printed? python def f(): try: return 'a' finally: print('f', end=' ') print(f())
- What is printed? python def g(): x = yield 1 print('got', x) y = yield x 2 print('got', y) it = g() print(next(it)) print(it.send(5)) try…