IndexError
This error occurs when you attempt to access an item from a list or tuple using an index that is outside the range of its populated elements.
Usually happens because:
- ☑ Target query index is equal to or greater than the sequence length
- ☑ Attempting to query indices on empty lists or tuple records
- ☑ Negative index query wraps beyond the negative size boundaries
🔍 Quick Checklist:
What is IndexError?
An 'IndexError' is raised at runtime when you attempt to retrieve or mutate an item in a sequence collection (such as a list, tuple, range, or string) using an integer index that is less than the negative length of the sequence or greater than or equal to its positive length. Modern Python versions (Python 3.11+) provide enhanced error traceback logs pointing to the exact subscript brackets causing the out-of-bounds access.
Common Causes
- Accessing index equal to or greater than length: Requesting 'items[len(items)]' (since indexing is 0-based, the maximum index is 'len - 1').
- Accessing index on empty list: Attempting to read index 0 from a list that contains zero items.
- Incorrect negative offset indexing: Using negative values (like '-5' on a list of length 3) that exceed the sequence offset limits.
| Cause | Frequency |
|---|---|
| Accessing index equal to or greater than list length | ⭐⭐⭐⭐⭐ |
| Attempting to index an empty list collection | ⭐⭐⭐⭐ |
| Negative index offset exceeding negative length | ⭐⭐⭐ |
Common Mistakes
- Using loop index iterators (like `for i in range(len(items)):`) and then modifying or populating the list length inside the loop body, causing indices mismatch crashes.
- Forgetting that `list.pop()` raises an IndexError if the list is empty.
How to Fix
Python Operations & Verification
Verify index query limits against the list length before accessing elements.
items = [10, 20, 30]
index_to_query = 3
if 0 <= index_to_query < len(items):
print(f"Value: {items[index_to_query]}")
else:
print(f"Index {index_to_query} is out of bounds. List length: {len(items)}")Platform Specific Fixes
Verify list operations in interactive console shells.
python3 -c "items = [1, 2]; print(items[-1])"Best Practices
- Prefer direct iteration over elements (`for item in items:`) instead of manually tracking numeric indices.
- Use helper defaults getters (like `next(iter(items), default)`) to safely extract the first element of a sequence.
Frequently Asked Questions (FAQ)
Q: What is an IndexError?
It is a runtime error raised when you attempt to access a list or tuple element using a numeric index that does not exist in the collection.
Q: How do I prevent 'IndexError: list index out of range'?
Ensure that your index is within the boundaries of the list. You can check the length using 'len(my_list)' or verify the list is not empty using 'if my_list:'.
Q: How does negative indexing work in Python?
Negative indices count backwards from the end of the collection (e.g. '-1' is the last item, '-2' is the second-to-last item). If the negative index exceeds the negative length, an IndexError is raised.
Q: Why do slices not throw an IndexError?
Python's slicing syntax (e.g. 'my_list[0:100]') is designed to be forgiving. If the slice range exceeds the list length, it simply returns whatever items are available (or an empty list if starting out of bounds) without raising an exception.