ProgrammingHardGATE CS · Product-company placement

What is printed?

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

Correct answer: C. [1, 2] [3] [1, 2]

The None sentinel gives every default call a fresh list, so f(3) returns [3]. f(2, r) appends to the list r refers to, so r prints [1, 2].

More Python Programming questions

Exams that ask this topic