ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
d = {'a': 1, 'b': 2, 'c': 3}
try:
    for k in d:
        if d[k] == 2:
            del d[k]
except RuntimeError:
    print('error')
print(len(d))
  1. A. error | 3
  2. B. error | 2
  3. C. no error | 2
  4. D. error | 1

Correct answer: B. error | 2

Deleting from a dict while iterating over it makes the next step raise RuntimeError, so the except branch runs. The deletion of b has already happened, so the length is 2.

More Python Programming questions

Exams that ask this topic