PCEP-30-02 practice question 5 of 35

This question is a tricky one. What is the result of the following code snippet? numbers = [1, 2, 3, 4, 5] result = [] for number in numbers: result.append(numbers.pop()) print(result)

Full set: 548 questions

Domain Data Collections – Tuples, Dictionaries, Lists, and Strings

Answer options
A: [1, 2, 3, 4, 5]
B: [3, 4, 5]
C: [5, 4, 3] Correct answer
D: [5, 4, 3, 2, 1]
Correct Answer:
C. [5, 4, 3]
Explanation

This code demonstrates the unpredictable behavior of modifying a list while iterating over it with a for loop. The loop's iterator and the list's length change concurrently.
1. Iteration 1: number is 1. numbers.pop() removes and returns the last element, 5. numbers becomes [1, 2, 3, 4]. result becomes [5].
2. Iteration 2: The iterator advances to the second position. number is 2. numbers.pop() removes 4. numbers becomes [1, 2, 3]. result becomes [5, 4].
3. Iteration 3: The iterator advances to the third position. number is 3. numbers.pop() removes 3. numbers becomes [1, 2]. result becomes [5, 4, 3]. At this point, the iterator attempts to advance to the fourth position, but the list now only has two elements. The loop condition is no longer met, and the loop terminates.

Why Incorrect

A. [1, 2, 3, 4, 5] is incorrect. This would be the output if the code appended the loop variable number to result without modifying the numbers list.
B. [3, 4, 5] is incorrect. The numbers are correct, but the order is wrong. pop() removes from the end, so 5 is the first element appended.
D. [5, 4, 3, 2, 1] is incorrect. This would be the result if the loop completed all five iterations, which it does not because the list is shortened during iteration.

References

1. Python 3.12.3 Documentation, The Python Tutorial, Section 4.2. for Statements: The official tutorial explicitly warns: "It is not safe to modify the sequence being iterated over in the loop... If you need to modify the list you are iterating over... you must iterate over a copy." This principle explains why the loop terminates prematurely.

2. Python 3.12.3 Documentation, The Python Tutorial, Section 5.1. More on Lists: This section details the list.pop([i]) method, stating: "If no index is specified, a.pop() removes and returns the last item in the list." This confirms that 5, then 4, then 3 are the elements being removed.

3. MIT OpenCourseWare, 6.0001 Introduction to Computer Science and Programming in Python, Fall 2016, Lecture 5 Notes: The course notes advise, "Never mutate a list as you are iterating over it," and provide a similar example (for e in L1: L1.remove(e)) to demonstrate how this leads to skipping elements because the list shrinks while the loop index advances.

Scroll to Top