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))

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

Exams that ask this topic