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))
  1. A. 1 1 1 1
  2. B. 1 2 1 1
  3. C. 1 2 1 3
  4. 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

Exams that ask this topic