PCEP-30-02 practice question 23 of 35

What is the result of the following code snippet? numbers = list(range(4)) for i in range(3): numbers.insert(-1, numbers[i]) print(numbers)

Full set: 548 questions

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

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

The code initializes a list numbers as [0, 1, 2, 3]. The for loop iterates three times with i taking values 0, 1, and 2. In each iteration, numbers.insert(-1, numbers[i]) inserts an element into the list. The index -1 specifies the position just before the last element.
1. i = 0: numbers.insert(-1, numbers[0]) inserts 0 before 3. The list becomes [0, 1, 2, 0, 3].
2. i = 1: numbers.insert(-1, numbers[1]) inserts 1 before 3. The list becomes [0, 1, 2, 0, 1, 3].
3. i = 2: numbers.insert(-1, numbers[2]) inserts 2 before 3. The list becomes [0, 1, 2, 0, 1, 2, 3]. The final print statement outputs this resulting list.

Why Incorrect

A. This option incorrectly includes values not generated by the loop and range(4), such as 4, and misrepresents the final structure of the list.
B. This option incorrectly omits the original last element, 3. The insert(-1, ...) operation always keeps the last element at the very end of the list.
D. This result does not logically follow from the operations. It seems to misunderstand both the values being inserted and the behavior of the insert() method.

References

1. Python Software Foundation. "The Python Tutorial". Section 5.1, "More on Lists". The documentation specifies that list.insert(i, x) inserts item x at position i. For i = -1, the insertion happens before the last element. Retrieved from: https://docs.python.org/3/tutorial/datastructures.html

2. Python Software Foundation. "The Python Standard Library". Section "Built-in Types", "Sequence Types — list, tuple, range". This section details that negative indices for sequences are counted from the right. Retrieved from: https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range

3. MIT OpenCourseWare. "6.0001 Introduction to Computer Science and Programming in Python, Fall 2016". Lecture 3 notes cover list objects and mutability, explaining that methods like insert modify the list object in place, which is critical to understanding the code's behavior within the loop. Retrieved from: https://ocw.mit.edu/courses/6-0001-introduction-to-computer-science-and-programming-in-python-fall-2016/resources/lecture-3/

Scroll to Top