ProgrammingModerateTCS NQT · Infosys pattern
What is printed?
What is printed?
a = [1, 2, 3, 4, 5, 6]
for x in a:
if x % 2 == 0:
a.remove(x)
print(a)- A. [1, 3, 5, 6]
- B. [1, 2, 3, 4, 5, 6]
- C. [1, 3, 5]
- D. [1, 3, 4, 5]
Correct answer: C. [1, 3, 5]
Removing while iterating shifts later elements left, so the loop skips the element after each removed one. Here 2 is removed (3 skipped), 4 removed (5 skipped), 6 removed – the result looks right only by luck. With [2, 4, 6, 8] the same loop leaves [4, 8]. Iterate over a copy or build a new list.
More Python Programming questions
- What is printed? python print(round(2.5), round(3.5), round(-0.5), int(-2.7), -7 // 2, -7 % 2)
- What is printed? python from collections import Counter c = Counter("mississippi") print(c.mostcommon(2), c["z"], sum(c.values()))
- What is printed? python a, b, c = range(6) x, y = y, x = 1, 2 print(a, b, c, x, y)
- What is printed? python words = ["banana", "Apple", "cherry", "apple"] print(sorted(words), sorted(words, key=str.lower)[:2], max(words…
- What is printed? python i = 10 squares = [i i for i in range(3)] for j in range(3): pass print(i, squares, j)
- What is printed? python s = " Hello, World " print(s.strip().lower().split(","), s.count("l"), s.find("z"), "-".join("abc"))