ProgrammingHardCAT · MBA placement

What is printed?

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

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

dict.fromkeys stores the same list object as the value for every key. Appending through one key therefore changes the value seen through the other key.

More Python Programming questions

Exams that ask this topic