Check a Python loop for an off-by-one error

← Back to Blog & Articles

An off-by-one error happens when a loop processes one more or one fewer item than intended. Python’s range function makes the endpoint convention especially important.

Worked example

range(3) produces zero, one, and two. Its stopping value is excluded. To print the numbers one through three, use a range that starts at one and stops before four. Both loops perform three iterations, but they expose different values inside the loop.

What to check

Write the expected sequence explicitly for a small input. Check zero iterations and one iteration before testing a larger loop. If you use a range to access list positions, remember that a list of length n has positions zero through n minus one. The position n is outside the list. Counting iterations and identifying the values used during those iterations are related questions that should each be checked.

Continue with the book

Explore the full treatment, worked examples, and exercises in Code Quest with Python.


Companion article for Code Quest with Python, published by Choral Software. Article text and original examples © 2026 Choral Software. All rights reserved.

Scroll to Top