ProgrammingVery hardGATE CS · Product-company placement

What is printed?

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

Correct answer: D. [0, 1] [0, 1] (0,) (0,)

For a list, += mutates the shared default in place, and both calls return that same object, printed after both ran: [0, 1] twice. For a tuple, += creates a new tuple, so the default () never changes.

More Python Programming questions

Exams that ask this topic