Stockertim Dictionary · Technology · Artificial intelligence
Off-by-one error
Also called off-by-one, OBOE, fencepost error
In short
A common coding mistake in which a loop, range, index or count starts or stops one step too early or too late, so an item is skipped or counted twice.
- Beginner
- Concept
- Checked
In detail
An off-by-one error arises wherever counting has a boundary. Code has to decide whether to start at zero or one and whether the end point is included, and getting either choice wrong shifts the result by exactly one item. The mistake is easy to make because both conventions are common and look almost identical on the page.
Python offers several places for it. Lists are indexed from zero, so the tenth item is at position 9. range(1, 12) yields 1 to 11, not 12, because the stop value is excluded, and a slice such as rows[0:10] returns ten rows, positions 0 to 9. Comparisons create the same trap: > 30 and >= 30 differ only for the value 30 itself, which is precisely the value a real data set is likely to contain.
The classic illustration is the fence: a straight fence 50 metres long with a post every 10 metres needs six posts, not five, because there is a post at each end. Counting the days in a period has the same shape; from the 1st to the 10th of a month inclusive is ten days, while the difference between the two dates is nine.
The error rarely causes a crash; it produces a total, a count or a date range that is slightly wrong, which is why it survives into reports. The defence is to test boundaries on purpose: build a tiny example with values exactly at the edges, work out the answer by hand and compare.
Worked example
A payroll assistant at a hotel in Mombasa writes code to pay casual staff for days worked from 1 to 15 November.
- The code uses
range(1, 15), which yields days 1 to 14: 15 − 1 = 14 days. - The correct count of days from 1 to 15 inclusive is 15 − 1 + 1 = 15 days.
- At KSh 1,000 a day each casual worker is underpaid 1 × KSh 1,000 = KSh 1,000.
Changing the code to range(1, 16) fixes the count, and a known-answer test for a three-day period is added to catch a repeat.
In practice
Reviewers look for off-by-one errors in loops, date ranges, list slices and threshold conditions, and AI-generated code deserves the same scrutiny. Spreadsheet users meet the same problem when a range stops one row short of the data or a formula counts days between dates instead of days inclusive.
Watch out
- The difference between two dates excludes one end; add one if both the first and last day count.
- Test values sitting exactly on a boundary, because that is where the error shows.
Learn it properly
Official sources
- Quality assurance of code for analysis and research · Government Analysis Function
Facts last checked on 9 November 2026.
Education, not advice: the Stockertim Dictionary explains what terms mean. It never recommends buying or selling anything.