Editor

IndexError: string index out of range

What it means

You asked for a character position the string does not have. Positions start at 0, so 'cat' has positions 0, 1 and 2, and an empty string '' has none. Slices such as text[0:10] never raise this error, only single positions like text[10] do.

1. Using `len()` as the last position

This raises the error

Broken
word = 'python'
last = word[len(word)]
print(last)
Output
Traceback (most recent call last):
  File "<exec>", line 2, in <module>
IndexError: string index out of range

The fix

Fixed
word = 'python'
last = word[len(word) - 1] # or simply word[-1]
print(last, word[-1])
Output
n n

len(word) is 6, but the positions run from 0 to 5. Use len(word) - 1, or -1, which always means the last character.

Try fixing it yourself in the editor

2. An empty string

This raises the error

Broken
name = ''
initial = name[0]
print(initial)
Output
Traceback (most recent call last):
  File "<exec>", line 2, in <module>
IndexError: string index out of range

The fix

Fixed
name = ''
initial = name[0] if name else '?'
print(initial)
print(repr(name[:1])) # a slice gives '' instead of an error
Output
?
''

An empty string has no first character. Check it first, or use a slice like name[:1], which returns an empty string instead of failing.

Try fixing it yourself in the editor

3. Comparing each character with the next one

This raises the error

Broken
text = 'balloon'
for i in range(len(text)):
if text[i] == text[i + 1]:
print('double', text[i])
Output
double l
double o
Traceback (most recent call last):
  File "<exec>", line 3, in <module>
IndexError: string index out of range

The fix

Fixed
text = 'balloon'
for i in range(len(text) - 1): # stop one early
if text[i] == text[i + 1]:
print('double', text[i])
Output
double l
double o

When the loop reads text[i + 1], the last character has no next one. Stopping at len(text) - 1 keeps both positions inside the string.

Try fixing it yourself in the editor

When you see this error, check

  • Print repr(text) and len(text) just before the failing line: repr() shows an empty string as ''.
  • Use text[-1] for the last character.
  • Check if text: before reading text[0].
  • Use a slice like text[:1] when an empty result is fine.

All Python errors · How to read a traceback · Step through your code