Why does a Python slice stop before its ending index?
Quick answer
Python slices include the start index but exclude the stop index. So items[1:3] takes the items at indexes 1 and 2, not index 3. Think of the stop as the boundary just after the last item you want. To include the item at index 3, use items[1:4]; the stop can be the sequence length when you want to reach its end. [S1]
The question, the details, the next step.
A practical checklist
Write the list items beside their indexes.
Mark the start: that item is included.
Treat the stop as a boundary; its index is excluded.
To include a desired final index, set the stop one higher.
Trace the selected indexes and compare them with the items you intended.
A few more useful answers
Does the stop index refer to an item or a position?
Treat it as the position before which the slice stops. The item at the stop index is not included. [S1]
Can I use the list length as the stop?
Yes. A slice’s end boundary can equal the sequence length, letting the slice reach the end. [S1]
What is the quickest way to remember the rule?
Think “start here, stop before there.” To include the item at index 3, use stop boundary 4. [S1]
Sources
References used for this guide.
- [S1] An Informal Introduction to Python — sequence slicing docs.python.org · Checked
