← Back

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

  1. Label each element with its index before reading the slice.
  2. Include the start index, exclude the stop: [a:b] collects positions a, a+1, ..., b-1.
  3. Compute the expected length as b - a and check the collected values against it.
  4. Apply the defaults for omitted ends: [:k] starts at 0, [k:] runs to the end, [:] copies everything.

Common wrong fixes

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.

Solve it in the interactive editor β†’

πŸ“¦ Learning path: Lists and Dictionaries

Problem 4 of 20 in this path. Work them in order β€” each one builds on the rule before it.

← Negative indexingNext in path: Next problem β†’

More lists problems

Keep going