Write Python. Understand every error.

Open the editor

Error guide · IndexError

IndexError: string index out of range

You asked for a character at a position the text does not have.

Example

word = "cat"
print(word[3])

What Python says

IndexError: string index out of range

As printed by Python 3.12. Other versions may word it slightly differently.

Try this code in Py-CRAFT

Why it happens

Positions in text start at 0, so a three-letter word has positions 0, 1 and 2. Position 3 is one past the end. A loop that runs to len(word) using <= instead of < causes the same error.

How to fix it

word = "cat"
print(word[2])
print(word[-1])

Output: t ⏎ t

Tips

Learn the ideas behind it

Other common errors

Share this page: