ProgrammingHardGATE CS · Product-company placement

What is printed?

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

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

setdefault inserts the default only when the key is missing and always returns the stored value. The second call ignores [9] and returns the existing list, so 2 is appended to it.

More Python Programming questions

Exams that ask this topic