ProgrammingHardAccenture pattern

What is printed?

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

Correct answer: B. {'a': [1, 2], 'b': [3]}

setdefault('a', []) creates the list [] only the FIRST time key 'a' is missing, then returns the SAME existing list on later calls; so both appends to 'a' go to one shared list, giving [1, 2]. 'b' gets its own fresh list with just 3.

More Python Programming questions

Exams that ask this topic