IndexError
IndexError: string index out of range
Traceback
Traceback (most recent call last):
File "main.py", line 2, in <module>
print(s[5])
IndexError: string index out of rangeWhat causes this error
A string was accessed with an index that exceeds its length. The string is shorter than expected, or an off-by-one error in index calculation.
How to fix it
Check `len(string)` before indexing. Use string slicing instead of indexing (it returns empty string instead of raising). Validate input length before processing characters by position.
Code that causes this error
s = "hi" print(s[5])
Fixed code
s = "hi"
if len(s) > 5:
print(s[5])
else:
print(s[-1] if s else "empty string")About IndexError
This IndexError variant occurs when accessing a character in a string at an index beyond its length. Strings in Python are sequences and support the same indexing as lists, with valid indices from 0 to len(s)-1 and negative indices from -1 to -len(s). This error often appears when processing user input or external data that is shorter than expected, when manipulating strings character by character, and when assuming a minimum string length without validation.
Unlike lists, strings are immutable, so you cannot fix an out-of-range access by extending the string — you need to check the length first. The fix is the same as for list index errors: validate the index against `len()` before accessing, or use slicing (which never raises IndexError — `s[100:200]` on a short string returns an empty string).
Common scenarios
Accessing list elements beyond the list's actual length
Off-by-one errors in loop index calculations
Processing data with fewer elements than expected
Using hardcoded indices on dynamically-sized collections