Lists & Tuples · Question 17 · Hard

Even numbers are removed from a list while a for loop is running over it. What is printed?

nums = [2, 4, 6, 7]
for n in nums:
    if n % 2 == 0:
        nums.remove(n)
print(nums)
  1. [7]
  2. [4, 6, 7]
  3. RuntimeError
  4. [4, 7]
Answer and explanation

Answer: D. [4, 7]

Explanation: The loop walks by index. After 2 is removed the list is [4, 6, 7] and the loop moves to index 1, which is now 6, skipping 4. Removing 6 leaves [4, 7], and index 2 no longer exists, so the loop ends.

Previous: The list a is extended once with + and once with += through a second name… · Next: Student records are sorted by marks in descending order using a key. In what…

Practise lists & tuples

Try a fresh set of lists & tuples questions with an explanation after every answer, free and without signing up: Lists & Tuples practice. Or sit a full placement mock test.

More lists & tuples questions

More python practice

Dictionaries & Sets · Conditions & Loops · Functions & Scope · Comprehensions & Generators · Classes & Objects · Exceptions & Files · Built-ins & Standard Library · Variables, Types & Operators

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge