# Off-by-One Error

> A loop or count that goes one step too far or stops one step short.

**Field:** Software Development  
**Category:** Programming Concepts  
**Also known as:** Off by One, OBOE, Fencepost Error

## Think of it like

It is like posts in a fence. Ten gaps need eleven posts, and people often say ten.

## Definition

An off-by-one error is a count or a loop that goes one step too far or stops one step short. It often comes from starting at 0 or 1, or from mixing up less than and less than or equal to. Lists in most languages start at index 0, so the last item of 5 is at index 4. Reading index 5 goes past the end.

## Example

Jack's loop runs while i <= 5 over a list of 5 names. It reaches index 5, which does not exist, and the app crashes.

## Example code

```python
names = ["Ana", "Ben", "Cy", "Di", "Ed"]
for i in range(5):
    print(names[i])   # 0 to 4, right
print(names[5])       # IndexError
```

range(5) gives 0 to 4. Index 5 is one past the end.

## Why it matters

It is one of the most common bugs in all of coding. It hides at the edges, so a quick test of the middle misses it.

## Common mistake

Testing only with a typical list. Try an empty list, one item and the very last item.

## Three principles

- **Edges matter.** The first and last steps go wrong.
- **Zero-based count.** Five items end at index 4.
- **Check < and <=.** One sign moves the end by one.

## Related terms

- [Logic Error](https://learn.benibix.com/term/development/logic-error)
- [Index](https://learn.benibix.com/term/development/index)
- [Array](https://learn.benibix.com/term/development/array)
- [For Loop](https://learn.benibix.com/term/development/for-loop)
- [Loop](https://learn.benibix.com/term/development/loop)
- [Bug](https://learn.benibix.com/term/development/bug)
- [Edge Case](https://learn.benibix.com/term/design/edge-case)

## Taught in

- [Bugs and Error Types](https://learn.benibix.com/learn/development-concepts/bugs-and-error-types): Programming Basics, 15/18

![A row of five boxes holding letters, with positions 0 to 4 under them. A correct loop marks positions 0 to 4. A wrong loop that uses less than or equal to 5 reaches a sixth, empty spot past the end, marked with a cross.](https://learn.benibix.com/diagrams/dev7-off-by-one.svg)

---

Source: https://learn.benibix.com/term/development/off-by-one-error
Author: Behnia Zarei (a developer in Vienna, Austria, who builds and teaches data, AI and business intelligence at BENIBIX)
Publisher: BENIBIX Learn (https://learn.benibix.com/)
Last updated: 2026-11-17
Licence: CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Quote freely with attribution.
