ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
def add(x, memo={}):
    memo[x] = len(memo)
    return memo
print(add(5), add(7))
  1. A. {5: 0} {7: 0}
  2. B. {5: 0} {5: 0, 7: 1}
  3. C. {5: 0, 7: 1} {7: 1}
  4. D. {5: 0, 7: 1} {5: 0, 7: 1}

Correct answer: D. {5: 0, 7: 1} {5: 0, 7: 1}

The default dict is created once and shared by all calls. Both calls return that same object, and print runs after both calls, so both values show the final contents.

More Python Programming questions

Exams that ask this topic