PCEP-30-02 · Question #53
l1 = [1, 2, 3] for v in range(len(l1)): l1.insert(1, l1[v]) print(l1)
The correct answer is C. [1, 1, 1, 1, 2, 3]. Option C is correct because range(len(l1)) is evaluated once before the loop starts, locking in 3 iterations - but the list grows with each insert(1, ...) call, shifting elements right. Tracing it: v=0 reads l1[0]=1 → [1,1,2,3]; v=1 reads l1[1]=1 (still 1, since the new element…
Question
Options
- A[1, 2, 3, 1, 2, 3]
- B[3, 2, 1, 1, 2, 3]
- C[1, 1, 1, 1, 2, 3]
- D[1, 2, 3, 3, 2, 1]
How the community answered
(32 responses)- A6% (2)
- B13% (4)
- C78% (25)
- D3% (1)
Explanation
Option C is correct because range(len(l1)) is evaluated once before the loop starts, locking in 3 iterations - but the list grows with each insert(1, ...) call, shifting elements right. Tracing it: v=0 reads l1[0]=1 → [1,1,2,3]; v=1 reads l1[1]=1 (still 1, since the new element shifted things) → [1,1,1,2,3]; v=2 reads l1[2]=1 (again 1) → [1,1,1,1,2,3]. The critical trick is that inserting at index 1 keeps pushing the original 2 and 3 rightward, so l1[v] keeps landing on a 1 for all three iterations.
Distractors: A and D ([1,2,3,1,2,3] and [1,2,3,3,2,1]) assume elements are appended or reversed rather than inserted mid-list. B ([3,2,1,1,2,3]) mistakes this for a reversal operation.
Memory tip: When you see insert inside a loop that's iterating with an index, ask "what does l1[v] actually point to after the list has grown?" - the index v chases a moving target, and here it keeps catching 1 every time.
Community Discussion
No community discussion yet for this question.