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)- A. 1 RuntimeError / [1, 3, 5, 6]
- B. 2 RuntimeError / [1, 3, 5, 6]
- C. 2 RuntimeError / [1, 3, 5]
- 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
- What is printed? python words = ['bb', 'a', 'cc', 'd', 'aa'] print(sorted(words, key=len, reverse=True)) print(sorted(words, key=lambda w…
- What is printed? python a = list(range(6)) a[1:4] = 'xy' print(a) try: a[::2] = [0, 0] except ValueError as e: print('VE') a[2:2] = [7]…
- What is printed? python a = [1, 2, 3] b = a b += [4] c = a c = c + [5] print(a, c)
- What is printed? python d = {'a': 1, 'b': 2} d['c'] = 3 del d['a'] d['a'] = 9 print(list(d.items()))
- What is printed? python s = "a,b,,c" print(s.split(','), s.split(',', 1), " x y ".split())
- What is printed? python print(list(zip('abc', range(5))), dict(zip('ab', [1, 2, 3])))