ProgrammingModerateTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
d = {}
d.setdefault('k', []).append(1)
d.setdefault('k', []).append(2)
print(d)
  1. A. {'k': [1, 2]}
  2. B. {'k': [2]}
  3. C. {'k': [1]}
  4. D. {'k': [1, 2], 'k': []}

Correct answer: A. {'k': [1, 2]}

setdefault returns the existing list when the key is present, so both appends go into the same list.

More Python Programming questions

Exams that ask this topic