Home βΊ Problems βΊ Slicing does not include the end index
Slicing does not include the end index
π§ Predict the output Topic: lists Difficulty: easy Free
What this problem practises
Lists are mutable and assigned by reference. That one fact explains most list bugs: aliasing between what look like "copies", append() and sort() returning None, and slice boundaries that disagree with the index arithmetic.
This is an output-prediction problem: read the snippet carefully and write down exactly what it prints before anything runs. These questions are interview staples because they test whether you know the language rules, or merely recognise their syntax.
Difficulty: easy β the fix or the trick is normally a single line, and a careful read should be enough.
The challenge
The code runs in PyDebugβs in-browser compiler. Open the problem, run the snippet, watch the exact error or output, and keep iterating until it is right. Signed-in solves count toward XP and your daily streak.
The snippet
The interactive editor pre-fills exactly this code β read it, then submit your prediction:
nums = [10, 20, 30, 40, 50]
print(nums[1:3])
print(nums[:2])
print(nums[-2:])Understand the rule
items[1:3] returns exactly two elements β positions 1 and 2, never position 3. Python slices are half-open intervals: closed at the start, open at the stop. This convention is deliberate: the result length is stop minus start, adjacent slices [0:k] and [k:n] tile the list with no overlap, and empty slices are expressible. Every prediction here follows from that single rule.
How to trace it
- Label each element with its index before reading the slice.
- Include the start index, exclude the stop: [a:b] collects positions a, a+1, ..., b-1.
- Compute the expected length as b - a and check the collected values against it.
- Apply the defaults for omitted ends: [:k] starts at 0, [k:] runs to the end, [:] copies everything.
Common wrong fixes
- Counting inclusively on both ends and predicting one element too many.
- Expecting an out-of-range stop to crash; slices clamp silently, so items[1:99] just runs to the end.
- Confusing the element at the stop index with the last element of the result β they differ by one.
Rule to remember
Slices include start, exclude stop, and have length stop - start. If your predicted slice contains the element at the stop index, the prediction is wrong.
π¦ Learning path: Lists and Dictionaries
Problem 4 of 20 in this path. Work them in order β each one builds on the rule before it.
More lists problems
Keep going
- Output-prediction strategies β how to predict tricky snippets without running them.
- Browse every lists problem in this topic.
- Common Python errors and what they actually mean, plus the Python glossary for any term used on this page.