Off-by-One Errors
An off-by-one error happens when a loop runs one time too few or one time too many.
These errors are common because Python often starts counting at 0 and stops
before the end value.
The range Rule
range(5)
produces:
0, 1, 2, 3, 4
It does not include 5.
That is useful once you expect it, but surprising before you do.
Counting Items
Suppose you want to print five positions:
This prints five values:
0
1
2
3
4
The last index is 4, but the count of printed values is 5.
Inclusive Human Language
Human language often says "from 1 to 5" and means:
1, 2, 3, 4, 5
Python's range(1, 5) gives:
1, 2, 3, 4
To include 5, write:
range(1, 6)
Inclusive and exclusive endpoints
The stop value is not included.
Ready to run.
Debugging the Boundary
When a loop seems wrong, print the first and last few values.
Ask:
- What is the first value?
- What is the last value?
- How many values ran?
- Did I mean count or index?
These questions prevent many shape and indexing errors later in NumPy.
Check the First and Last Iteration
Confusing count with last index:
values = [10, 20, 30]
There are 3 values, but the last index is 2.
Which stop value should complete the loop so it prints 1, 2, 3, 4, 5?
Compute it first, then check your number.
HintChoose one past the endpoint
A range excludes its stop value, so choose the integer immediately after
5.
SolutionUse six
range(1, 6) produces 1, 2, 3, 4, 5. The stop value 6 is not included.
Boundaries Deserve Explicit Checks
When a loop boundary feels uncertain, write the smallest example and print the values. Guessing at boundaries is how off-by-one errors survive.