ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

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

Correct answer: D. 1 1 2

The second call passes a fresh list, so its length is 1. The first and third calls share the default list, which holds [1] and then [1, 3], so the third call returns 2.

More Python Programming questions

Exams that ask this topic