ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

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

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

fromkeys stores the same list object as the value for every key. Appending through one key changes the list that the other key also refers to.

More Python Programming questions

Exams that ask this topic