Index Out of Range Errors and Off-by-One Bugs: How to Find and Fix Them
What IndexError, ArrayIndexOutOfBoundsException and Go's index out of range panic mean, the off-by-one patterns that cause them, half-open ranges, and habits that make these bugs rare.
By Software Side Hustles Editorial Team · Published · Updated · 5 min read
Quick answer: you accessed position i in a sequence that has no position i. Indexes run from 0 to length - 1, so the usual culprits are a loop condition with <= instead of <, using len(items) as an index, an empty list, or a list that is shorter than you assumed. Print the index and the length on the failing line, then fix the boundary.
The error in each language
| Language | Message |
|---|---|
| Python | IndexError: list index out of range |
| Java (arrays) | ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5 |
| Java (lists) | IndexOutOfBoundsException: Index 0 out of bounds for length 0 |
| C# | IndexOutOfRangeException: Index was outside the bounds of the array. |
| Go | panic: runtime error: index out of range [5] with length 5 |
| Rust | index out of bounds: the len is 5 but the index is 5 |
| JavaScript | No error — you get undefined, and a TypeError later |
| C / C++ | No error — undefined behaviour, possibly a crash or silent corruption |
Java, Go and Rust tell you both the index and the length. "Index 5, length 5" is the signature of an off-by-one: the last valid index was 4.
The most common off-by-one patterns
1. <= in a loop condition
for (int i = 0; i <= arr.length; i++) { // last iteration: i == arr.length total += arr[i];}Use <, or better, a loop that cannot get the boundary wrong: for (int x : arr) in Java, for x in items in Python, for (const x of items) in JavaScript.
2. Using the length as an index
last = items[len(items)] # IndexErrorlast = items[len(items) - 1] # correctlast = items[-1] # idiomatic PythonJavaScript has items.at(-1) for the same purpose.
3. Assuming the list is not empty
first = results[0] # IndexError when the query returned nothingAn empty list is the most common input that nobody tests. Handle it explicitly — if not results: — or use next(iter(results), None) to get None instead of an exception.
4. Looking ahead past the end
for i in range(len(prices)): change = prices[i + 1] - prices[i] # fails on the last iWhen comparing neighbours, loop to len - 1, or iterate pairs: for a, b in zip(prices, prices[1:]): (or itertools.pairwise(prices) on Python 3.10+).
5. Parallel lists of different lengths
Indexing names[i] and scores[i] in the same loop fails when one list is shorter. zip(names, scores) stops at the shorter list; zip(names, scores, strict=True) (Python 3.10+) raises an error if lengths differ, which is usually what you want.
6. Splitting strings that do not have the expected shape
name, domain = email.split("@") # ValueError if there is no @, or twoparts = line.split(",")city = parts[3] # IndexError on a short lineValidate the number of parts before indexing. See how to split a string.
Half-open ranges: why range(0, n) stops at n − 1
Most languages describe ranges as half-open: the start is included, the end is excluded.
range(0, 5)→0, 1, 2, 3, 4items[2:5]→ indexes 2, 3, 4s.substring(2, 5)in Java and JavaScript → characters 2, 3, 4
This convention has useful properties: the length of [a, b) is b − a, and [a, b) plus [b, c) covers [a, c) with no overlap or gap. If you remember that the end is exclusive, slicing and pagination maths become consistent. Pagination is a classic case: page p (starting at 0) of size n covers items p * n up to, but excluding, (p + 1) * n.
The fencepost problem
A 10-metre fence with a post every metre needs 11 posts, not 10. The same mistake appears in code as "how many items between index 3 and index 7 inclusive?" — the answer is 7 − 3 + 1 = 5. When counting inclusive ranges, add one; when using half-open ranges, do not.
Off-by-one bugs without an error
Python's negative indexes make some bugs silent:
i = 0previous = items[i - 1] # items[-1]: the LAST element, not an errorAnd in binary search, a wrong boundary often causes an infinite loop or a missed element rather than an exception:
lo, hi = 0, len(a) - 1while lo <= hi: # <= because hi is inclusive here mid = (lo + hi) // 2 if a[mid] < target: lo = mid + 1 # +1, or the loop may never end elif a[mid] > target: hi = mid - 1 else: return midChoose one convention (inclusive hi with <=, or exclusive hi with <) and apply it consistently. Mixing them is where binary search bugs come from.
Habits that prevent index errors
- Prefer iteration over indexes —
for x in items,enumerate,zip,map,filter. - Test boundaries deliberately: empty input, one element, two elements, and the maximum size. See how to write good unit tests.
- Use safe accessors where "missing" is normal:
items.get(i)patterns,next(iter(xs), None),Optionalin Java streams (findFirst()). - Name boundaries clearly:
end_exclusiveorlast_indextells the reader which convention you used. - Let tools help: Rust and Go bounds-check at runtime; sanitizers (AddressSanitizer) catch out-of-bounds access in C and C++.
Frequently asked questions
Why does JavaScript not throw an index error?
Arrays are objects, and reading a property that does not exist returns undefined. The failure surfaces later as Cannot read properties of undefined. See that error explained.
How do I safely get an element that might not exist in Python?
items[i] if 0 <= i < len(items) else None, or catch IndexError. For the first element, next(iter(items), None).
Is IndexError the same as KeyError?
No. IndexError is for sequences indexed by position; KeyError is for dictionaries looked up by key.
Where this skill pays off
Boundary bugs are one of the most common faults in AI-generated code, and our free maximum subarray exercise hides one inside a fast-looking solution. Spotting the off-by-one in a confident answer — and naming the input that breaks it — is the core skill AI evaluation platforms test for. See how to prepare for technical AI evaluation work.