SoftwareSideHustles
Debugging

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

LanguageMessage
PythonIndexError: 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.
Gopanic: runtime error: index out of range [5] with length 5
Rustindex out of bounds: the len is 5 but the index is 5
JavaScriptNo 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

java
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

python
last = items[len(items)] # IndexError
last = items[len(items) - 1] # correct
last = items[-1] # idiomatic Python

JavaScript has items.at(-1) for the same purpose.

3. Assuming the list is not empty

python
first = results[0] # IndexError when the query returned nothing

An 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

python
for i in range(len(prices)):
change = prices[i + 1] - prices[i] # fails on the last i

When 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

python
name, domain = email.split("@") # ValueError if there is no @, or two
parts = line.split(",")
city = parts[3] # IndexError on a short line

Validate 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, 4
  • items[2:5] → indexes 2, 3, 4
  • s.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:

python
i = 0
previous = items[i - 1] # items[-1]: the LAST element, not an error

And in binary search, a wrong boundary often causes an infinite loop or a missed element rather than an exception:

python
lo, hi = 0, len(a) - 1
while 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 mid

Choose 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

  1. Prefer iteration over indexes — for x in items, enumerate, zip, map, filter.
  2. Test boundaries deliberately: empty input, one element, two elements, and the maximum size. See how to write good unit tests.
  3. Use safe accessors where "missing" is normal: items.get(i) patterns, next(iter(xs), None), Optional in Java streams (findFirst()).
  4. Name boundaries clearly: end_exclusive or last_index tells the reader which convention you used.
  5. 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.

Cookies on this site

We use essential cookies to run the questionnaire, practice labs and sign-in. With your permission we'd also like to use analytics to understand which pages help people, and advertising cookies to measure our Google Ads. Rejecting never limits any feature. Cookie policy