ProgrammingHardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
d = {1: 1}
try:
    for k in d:
        d[k + 1] = 0
except RuntimeError as e:
    print(e)
  1. A. No error
  2. B. dictionary changed size during iteration
  3. C. dictionary keys changed during iteration
  4. D. [1, 2]

Correct answer: B. dictionary changed size during iteration

Inserting a new key while iterating a dict raises RuntimeError on the next step. Iterate over list(d) instead if you need to add keys.

More Python Programming questions

Exams that ask this topic