PCEP-30-02 · Question #45
What is the expected output of the following code? numbers = [1, 2, 3, 4, 5] nums = numbers[2 : ] print(nums)
The correct answer is B. [3, 4, 5]. numbers[2:] uses Python's list slicing syntax, which extracts elements starting at index 2 through the end of the list. Since Python uses zero-based indexing, index 2 holds the value 3, so the slice returns [3, 4, 5] - making B correct. Why the distractors are wrong: A ([2])…
Question
Options
- A[2]
- B[3, 4, 5]
- CThe program will cause an error.
- D[2, 3, 4, 5]
How the community answered
(59 responses)- A10% (6)
- B69% (41)
- C5% (3)
- D15% (9)
Explanation
numbers[2:] uses Python's list slicing syntax, which extracts elements starting at index 2 through the end of the list. Since Python uses zero-based indexing, index 2 holds the value 3, so the slice returns [3, 4, 5] - making B correct.
Why the distractors are wrong:
- A (
[2]) confuses the slice index2with the value2; the number is an index position, not a filter. - D (
[2, 3, 4, 5]) is whatnumbers[1:]would return - off by one, since index 1 holds the value2. - C (error) is incorrect; Python handles out-of-range slice indices gracefully and never raises an error for slices.
Memory tip: Think of list[start:] as "start at this index, take everything after." Since Python counts from zero, [2:] means "skip the first 2 elements" - so [1, 2] are skipped and [3, 4, 5] remain.
Community Discussion
No community discussion yet for this question.