off-by-one error
A bug where a count or index is one too many or one too few, such as looping one step past the end.
In more detail
Zero-based indexing and ranges that exclude their end value make it easy to slip by one, for example writing < where <= was needed. Stating whether each bound is inclusive or exclusive prevents most such bugs. Testing the first, last and empty cases by hand catches the rest.
Related terms
- binary search — Finding a target in sorted data by comparing it with the middle item and throwing away the half where it cannot be.
- loop invariant — A statement about a loop's variables that is true before the loop starts and stays true after every iteration.
- string index — The position number of a character in a string or an item in a list, counting from 0 at the left, used in square brackets as s[0].
- range() — A built-in that produces a sequence of whole numbers on demand, such as range(5) for 0, 1, 2, 3, 4.
- slice — A copy of a run of items from a string, list or tuple, written s[start:stop], which includes start and stops just before stop.
Taught in
- Binary Search And Its Invariant — Algorithms & Data Structures for Working Engineers
- String Indices — Hands-on Python: Complete Video Course & Book
- Reading A Traceback Like A Professional — Hands-on Python: Complete Video Course & Book
- While, For, Range And The Loop Else — PCEP Certified Entry-Level Python Programmer (PCEP-30-02) Exam Prep
- Strings Sprint — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep