ProgrammingVery hardGATE CS · Product-company placement

What is printed?

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

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

Each call builds a new list and installs it as the new default via __defaults__. Even f(3, []), which ignores the default, stores [3] as the default, so f(4) returns [3, 4].

More Python Programming questions

Exams that ask this topic