PCEP-30-02 · Question #48
What is the expected output of the following code? x = [1, 2, 3, 4, 5, 6, 7, 8, 9] x[::2] = 10, 20, 30, 40, 50, 60 print(x)
The correct answer is C. The code is erroneous. C is correct because x[::2] selects every other element starting at index 0 - positions 0, 2, 4, 6, 8 - giving 5 slots to fill. The right-hand side 10, 20, 30, 40, 50, 60 is a 6-element tuple, which is a size mismatch. Python raises a ValueError: attempt to assign sequence of…
Question
Options
- A[1, 10, 3, 20, 5, 30, 7, 40, 9, 50, 60]
- B[1, 2, 10, 20, 30, 40, 50, 60]
- CThe code is erroneous.
- D[10, 2, 20, 4, 30, 6, 40, 8, 50, 60]
How the community answered
(51 responses)- A8% (4)
- B18% (9)
- C71% (36)
- D4% (2)
Explanation
C is correct because x[::2] selects every other element starting at index 0 - positions 0, 2, 4, 6, 8 - giving 5 slots to fill. The right-hand side 10, 20, 30, 40, 50, 60 is a 6-element tuple, which is a size mismatch. Python raises a ValueError: attempt to assign sequence of size 6 to extended slice of size 5 because extended slice assignment (step ≠ 1) requires an exact length match on both sides.
D is the "almost right" trap - it correctly shows what would happen if the RHS had 5 values (e.g., 10, 20, 30, 40, 50), replacing the 5 even-indexed positions. A and B reflect confused mental models of how slice assignment works and don't correspond to any valid Python behavior here.
Memory tip: Think "extended = exact." Basic slices (x[1:4]) can accept any length on the right (they resize the list), but extended slices (those with a step like [::2]) demand a one-for-one match - if the counts don't line up, Python errors out rather than guessing your intent.
Community Discussion
No community discussion yet for this question.