ProgrammingVery hardPython · GATE DA · Advanced

What is printed?

What is printed?
x = [1, 2, 3, 4, 5, 6]
for i in x:
    if i % 2 == 0:
        x.remove(i)
d = {'a': 1}
try:
    for k in d:
        d[k + 'x'] = 0
except RuntimeError as e:
    print(len(d), type(e).__name__)
print(x)
  1. A. 1 RuntimeError / [1, 3, 5, 6]
  2. B. 2 RuntimeError / [1, 3, 5, 6]
  3. C. 2 RuntimeError / [1, 3, 5]
  4. D. 1 RuntimeError / [1, 3, 5]

Correct answer: C. 2 RuntimeError / [1, 3, 5]

Removing while iterating shifts the list under the iterator: it visits 1, 2 (removed), then 4 (the 3 is skipped), then 6 after another shift, leaving [1, 3, 5]. Adding a key during dict iteration raises RuntimeError at the next step, after the insert has already happened, so len(d) is 2.

More Python Programming questions

Exams that ask this topic