ProgrammingVery hardGATE CS · Product-company placement

What is printed?

What is printed?
d = {i: i * i for i in range(4)}
try:
    for k in d:
        if k == 1:
            del d[k]
except RuntimeError:
    print("RE", end=" ")
for k in list(d):
    if k % 2 == 0:
        d.pop(k)
print(d)
  1. A. {3: 9}
  2. B. RE {1: 1, 3: 9}
  3. C. RE {3: 9}
  4. D. RE {0: 0, 3: 9}

Correct answer: C. RE {3: 9}

Deleting during iteration over a dict changes its size and raises RuntimeError on the next step, but the deletion of key 1 already happened. Iterating over list(d) (a snapshot) is safe; it removes 0 and 2, leaving {3: 9}.

More Python Programming questions

Exams that ask this topic