ProgrammingVery hardGATE CS · Product-company placement

What is printed?

What is printed?
def make_acc():
    total = []
    def add(x):
        total.append(x)
        return sum(total)
    def reset():
        nonlocal total
        total = []
    return add, reset
add, reset = make_acc()
add(5); add(5)
saved = add.__closure__[0].cell_contents
reset()
print(add(1), saved, add.__closure__[0].cell_contents)
  1. A. 1 [5, 5] [1]
  2. B. 11 [5, 5, 1] [5, 5, 1]
  3. C. 1 [] [1]
  4. D. 11 [5, 5] [1]

Correct answer: A. 1 [5, 5] [1]

add and reset share the same cell for total. reset rebinds the cell to a new empty list, so add(1) returns 1. `saved` still references the old list object, which is not changed by the rebinding.

More Python Programming questions

Exams that ask this topic