PCEP-30-02 · Question #40
What is the expected output of the following code? a = [1, 2, 3, 4, 5] print(a[3:0:-1])
The correct answer is B. [4, 3, 2]. Option B is correct because Python's slice a[3:0:-1] starts at index 3 (value 4), steps backward by 1, and stops before reaching index 0 - meaning index 0 (value 1) is excluded. The slice collects indices 3, 2, 1 → values [4, 3, 2]. Why the distractors fail: A [4, 3, 2, 1]…
Question
Options
- A[4, 3, 2, 1]
- B[4, 3, 2]
- C[4, 3]
- DThe code is erroneous.
How the community answered
(61 responses)- A3% (2)
- B80% (49)
- C11% (7)
- D5% (3)
Explanation
Option B is correct because Python's slice a[3:0:-1] starts at index 3 (value 4), steps backward by 1, and stops before reaching index 0 - meaning index 0 (value 1) is excluded. The slice collects indices 3, 2, 1 → values [4, 3, 2].
Why the distractors fail:
- A
[4, 3, 2, 1]- This would requirea[3::-1](no stop index), which includes index 0 all the way to the beginning. - C
[4, 3]- This would requirea[3:1:-1], stopping before index 1 instead of index 0. - D - The code is perfectly valid Python; negative steps with slice notation are a core language feature.
Memory tip: The stop index in Python slices is always exclusive - think of it as a fence: you stop at the fence, never stepping on that post. With step=-1, you're walking backwards and stop just before the fence at index 0.
Community Discussion
No community discussion yet for this question.