ProgrammingHardGATE CS · Product-company placement

What is printed?

What is printed?
def f(a, b=[]):
    b = b or []
    b.append(a)
    return b
x = f(1)
y = f(2, [])
z = f(3, [0])
print(x, y, z, f.__defaults__)
  1. A. [1] [1, 2] [0, 3] ([1],)
  2. B. [1] [2] [0, 3] ([],)
  3. C. [1] [2] [0, 3] ([1],)
  4. D. [1] [2] [3] ([],)

Correct answer: B. [1] [2] [0, 3] ([],)

`b or []` replaces any falsy b (the empty default or an empty passed list) with a fresh list, so the default is never mutated. A non-empty list such as [0] is used as is.

More Python Programming questions

Exams that ask this topic