Skip to main content

What is an Off-by-One Error in Python? (Explained for Kids!)

ยท 4 min read
Serhii Hrekov
software engineer, creator, artist, programmer, projects founder

Have you ever counted your toys and accidentally said you had 11, but really only had 10? Thatโ€™s kind of what an off-by-one error is in Python!

Itโ€™s a tiny mistake where your program counts 1 too many or 1 too few. These mistakes are super common, even for professional programmers.


๐Ÿงฎ Example 1: Counting with Rangesโ€‹

Letโ€™s say you want to print numbers from 1 to 10.

for i in range(1, 11):
print(i)

โœ… This is correct because range(1, 11) means โ€œstart at 1, stop before 11โ€.

But if you write this:

for i in range(1, 10):
print(i)

โŒ You only get numbers 1 to 9 - you're missing number 10. Thatโ€™s an off-by-one error!


๐ŸŽ‚ Example 2: Getting the Last Item in a Listโ€‹

Hereโ€™s a list of your favorite cakes:

cakes = ["Chocolate", "Strawberry", "Vanilla", "Carrot"]

If you want the last cake, this is correct:

print(cakes[3])  # Carrot

โœ… Because the list starts at 0, the fourth item is at index 3.

But if you write:

print(cakes[4])

โŒ You get an error! There is no cake at number 4 - you went 1 too far. Another off-by-one error.


๐ŸŽ Why Does This Happen?โ€‹

Because Python starts counting at 0. Most people start counting at 1. Thatโ€™s why itโ€™s easy to get confused.

# Example
toys = ["Bear", "Car", "Doll"]
print(toys[0]) # "Bear", the first toy!

Always remember: Python starts at zero. So:

  • First item = index 0
  • Second item = index 1
  • Third item = index 2

๐Ÿ›  Tips to Avoid Off-by-One Errorsโ€‹

  • โœ… Always check if your loop should go to or before the last number.
  • โœ… Remember range(a, b) goes from a to b-1.
  • โœ… Check list lengths with len() before accessing an item.
  • โœ… Use -1 to get the last item in a list:
print(cakes[-1])  # Carrot

๐Ÿง Summaryโ€‹

Off-by-one errors are tiny counting mistakes in Python. They happen when:

  • You loop too far or not far enough
  • You access a list index thatโ€™s 1 too big or small

But now that you know about them, you can catch them like a debugging superhero ๐Ÿฆธโ€โ™‚๏ธ!

Happy coding! ๐ŸŽ‰