ProgrammingModerateTCS NQT · Infosys
What does this Python code print? def f(x, acc=[]): acc.append(x) return len(acc) print(f(1), f(2), f(3, []), f(4))
- A. 1 2 1 3
- B. 1 1 1 1
- C. 1 2 1 1
- D. 1 2 1 4
Correct answer: A. 1 2 1 3
The default list is created once at definition time, so calls that omit acc share it: f(1) gives 1, f(2) gives 2. f(3, []) uses a fresh list and gives 1, and f(4) returns to the shared list, which then has 3 items.
More Python Programming questions
- What is the output of this Python code? t = ([1], 5) try: t[0] += [2] except TypeError: print("err", end=" ") print(t)
- What does this Python code print? class A: items = [] n = 0 def add(self, x): self.items += [x] self.n += 1 a, b = A(), A() a.add(1)…
- What is printed? a = [1, 2, 3]; b = [2, 3, 4] g = (x for x in a if x in b) a = [9, 2, 3]; b = [1, 9, 3] print(list(g))
- What does this Python code print? def deco(tag): def wrap(fn): def inner(x): return "<" + tag + ">" + fn(x) + "</" + tag + ">" return…
- What does this Python code print? words = ["bb", "a", "ccc", "dd", "e", "fff"] print(sorted(words, key=len, reverse=True)[:3], min(words…
- What is printed? python def f(): for i in range(3): try: if i == 1: continue if i == 2: return 'ret' finally: print('f', i, end=' ')…