ProgrammingHardGATE CS · Product-company placement

What is printed?

What is printed?
d = dict.fromkeys(range(3), 0)
for k in d:
    d[k] += k
e = {k: [] for k in "ab"}
e["a"].append(1)
f = dict.fromkeys("ab", [])
f["a"].append(1)
print(d, e, f)
  1. A. {0: 0, 1: 1, 2: 2} {'a': [1], 'b': [1]} {'a': [1], 'b': [1]}
  2. B. {0: 0, 1: 1, 2: 2} {'a': [1], 'b': []} {'a': [1], 'b': []}
  3. C. {0: 0, 1: 1, 2: 2} {'a': [1], 'b': []} {'a': [1], 'b': [1]}
  4. D. RuntimeError

Correct answer: C. {0: 0, 1: 1, 2: 2} {'a': [1], 'b': []} {'a': [1], 'b': [1]}

Changing values while iterating is allowed (only size changes are not). fromkeys uses one shared object for every value, so a mutable default is shared, unlike a comprehension that builds a new list per key.

More Python Programming questions

Exams that ask this topic