PCEP-30-02 · Question #5
What is the output of the following snippet? ``python my_list = [1, 2] for v in range(2): my_list.insert(-1, my_list[v]) print(my_list) ``
The correct answer is B. [1, 1, 1, 2]. Option B is correct because insert(-1, x) places an element before the last item (index -1 acts as the target position being pushed right, not the insertion destination). After iteration 1 (v=0): my_list[0] is 1, inserted before 2 → [1, 1, 2]. In iteration 2 (v=1): my_list[1]…
Question
my_list = [1, 2]
for v in range(2):
my_list.insert(-1, my_list[v])
print(my_list)
Options
- A[1, 1, 2, 2]
- B[1, 1, 1, 2]
- C[1, 2, 1, 2]
- D[1, 2, 2, 2]
How the community answered
(29 responses)- A3% (1)
- B83% (24)
- C10% (3)
- D3% (1)
Explanation
Option B is correct because insert(-1, x) places an element before the last item (index -1 acts as the target position being pushed right, not the insertion destination). After iteration 1 (v=0): my_list[0] is 1, inserted before 2 → [1, 1, 2]. In iteration 2 (v=1): my_list[1] is now 1 (not 2!), inserted before 2 → [1, 1, 1, 2].
- A
[1, 1, 2, 2]is wrong because it assumesinsert(-1, ...)appends after the last element - it doesn't, it inserts before it, so2never gets duplicated at the end. - C
[1, 2, 1, 2]is wrong because it assumesmy_list[1]stays2throughout, ignoring that the list mutates during the loop. - D
[1, 2, 2, 2]is wrong because it assumes both iterations insert2, but after iteration 1 the list is[1, 1, 2], makingmy_list[1]equal to1, not2.
Memory tip: Think of insert(-1, x) as "cut in line just before the last person" - the last element (2) always stays last, and the index you read (my_list[v]) reflects the already-mutated list, not the original.
Community Discussion
No community discussion yet for this question.