Skip to content

Off-by-one error in range() loop

Quick summary

Your loop iterates one too few or one too many times because range() excludes the stop value — range(5) gives 0..4, not 0..5.

Why this happens

  • You used range(n) when you needed range(1, n+1) to include n, or range(n+1) to include 0 through n

  • You used range(1, n) when you needed range(1, n+1) to include the last element

  • You mixed zero-indexed and one-indexed thinking when setting the range start and stop values

Minimal example

✗ Broken code
# Sum 1 through 5, but range(1, 5) gives 1..4
total = sum(range(1, 5))
print(total)  # 10, expected 15
✓ Fixed code
# range(1, 6) gives 1..5, including 5
total = sum(range(1, 6))
print(total)  # 15

range(1, 6) includes 1 through 5 because the stop value is exclusive — adding 1 to the desired last value fixes the off-by-one.

How to diagnose

  • Print the actual values produced by range() to verify the sequence matches your expectation

  • Check the loop body for array indexing that assumes the loop includes the boundary value

  • Count the iterations and compare with the expected count to detect off-by-one errors

How to fix

  • Adjust the stop value: use range(n+1) if you need to include n, or range(n) if you need 0 through n-1

  • Use range(1, n+1) for 1-indexed loops that should include n, or range(len(items)) for index-based loops

  • Test the loop with a small input and print each iteration to verify the boundaries are correct

How to prevent

  • Always remember range(start, stop) includes start but excludes stop — test boundary values

  • Use enumerate() instead of range(len()) for index-based loops to avoid manual index management

Related Resources

Related Glossary

Related Lessons

  • Loops

    Learn about loops and range.

← Back to language