IndexError: list index out of range
Error message
list index out of range
Quick summary
You tried to access a list element at an index that is beyond the list's valid range (0 to `len(list) - 1`).
Why this happens
Index is greater than or equal to the list length
The list is empty but was accessed at index 0
Off-by-one error in a loop boundary (e.g.,
range(len(lst) + 1))
Minimal example
nums = [1, 2, 3]
print(nums[5])nums = [1, 2, 3]
print(nums[2])nums[5] is out of range — the list has 3 elements (indices 0–2). Use a valid index like nums[2] to access the last element.
How to diagnose
Print
len(lst)and the index being accessedCheck loop bounds — does the index stay within
0tolen(lst) - 1?Verify the list is not empty before accessing elements
How to fix
Check
if index < len(lst)before accessing the elementFix the loop boundary (use
range(len(lst)), notrange(len(lst) + 1))Use
try/except IndexErrorto handle the error gracefully
How to prevent
Prefer
for item in lstoverfor i in range(len(lst))when possibleCheck the list length before accessing by index
Related Resources
Related Lessons
- Conditions and Loops
Learn about loops and list iteration in Python
Related Practice
- Python Dynamic Typing
Understand Python's type system for lists.