nerdexam
Python_Institute

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

What is the output of the following snippet?
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)
  • A
    3% (1)
  • B
    83% (24)
  • C
    10% (3)
  • D
    3% (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 assumes insert(-1, ...) appends after the last element - it doesn't, it inserts before it, so 2 never gets duplicated at the end.
  • C [1, 2, 1, 2] is wrong because it assumes my_list[1] stays 2 throughout, ignoring that the list mutates during the loop.
  • D [1, 2, 2, 2] is wrong because it assumes both iterations insert 2, but after iteration 1 the list is [1, 1, 2], making my_list[1] equal to 1, not 2.

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.

Full PCEP-30-02 Practice