Why does `range(1, 5)` stop before 5 in a Python loop?
Quick answer
range(1, 5) produces 1, 2, 3, 4: the start is included, but the stop is excluded. If you want to count from 1 through 5, use range(1, 6). For a simple upward count by one, set the stop one greater than the last value you want included. Think of the stop as a boundary, not the final value in the sequence.
The question, the details, the next step.
A practical checklist
Write down the first value the loop should process.
Write down the last value you want included.
For an upward count by one, use a stop one greater than that last value.
Check that the range’s first and final included values match your intention.
If you use a different step or direction, work out the intended sequence rather than applying the simple +1 rule automatically.
A few more useful answers
What values does `range(1, 5)` produce?
It produces 1, 2, 3, 4; the stop value, 5, is excluded. [S1]
How do I include 5 in a range that starts at 1?
Use range(1, 6). This includes 5 while keeping the stop value excluded. [S1]
Does this explain all the rules for Python list slicing?
No. It explains the range stop and offers a boundary intuition, but does not establish slice behavior. Learn slicing separately when you need its specific rules.
Sources
References used for this guide.
- [S1] Python Tutorial: The range() function docs.python.org · Checked
