IndexError: list index out of range means you used an index that does not exist for the list. Python lists are zero-indexed: the first element is at index 0, the second at 1, and so on. Using an index equal to or greater than the list length raises this error. Here is how to avoid and fix it.
What this error means
For a list of length n, valid indices are 0 through n - 1. Negative indices count from the end: -1 is the last item, -2 the second-to-last. If you use an index outside that range—for example 3 on a list of length 3 (indices 0, 1, 2)—Python raises IndexError: list index out of range. The same idea applies to string index out of range for strings.
Common causes
- Index too large. You use an index ≥
len(list)(e.g.items[5]when the list has only 3 elements). - Using
len(list)as the index. The last valid index islen(list) - 1, notlen(list). - Empty list. Any positive index on
[]causes IndexError;[]has no “first” or “last” element by index. - Assumptions about data. The list comes from user input, a file, or an API and is shorter than you assumed.
Example that causes the error
items = [10, 20, 30]
print(items[3]) # IndexError: only indices 0, 1, 2 exist
Fix 1: check length before using an index
items = [10, 20, 30]
i = 3
if i < len(items):
print(items[i])
else:
print("Index", i, "doesn't exist")
Fix 2: access the last item safely
Use -1 for the last element. For an empty list, check first or use try/except.
items = [10, 20, 30]
last = items[-1] # 30
# If list might be empty:
if items:
last = items[-1]
else:
last = None
Fix 3: use try-except
items = [10, 20, 30]
try:
value = items[5]
except IndexError:
print("Index 5 is out of range")
value = None
Looping safely
When looping by index, use range(len(items)) so the index never goes out of range, or loop over the list directly: for x in items:. See Lists and loop with index for patterns.
Next steps: Errors & Exceptions · IndexError: string · Lists