ProgrammingHardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
def f(x, acc=[]):
    acc.append(x)
    return acc
f(1)
f(2)
print(f(3, []), f(4))
  1. A. [3] [4]
  2. B. [3] [1, 2, 4]
  3. C. [1, 2, 3] [1, 2, 4]
  4. D. [3] [1, 2]

Correct answer: B. [3] [1, 2, 4]

Passing [] explicitly creates a fresh list, so f(3, []) returns [3]. f(4) uses the default list, which already holds 1 and 2, so it returns [1, 2, 4].

More Python Programming questions

Exams that ask this topic