List index out of range
This error occurs when you attempt to retrieve or mutate an item in a list using an index that is outside its range of elements.
Usually happens because:
- ☑ Off-by-one calculations on loop indexes
- ☑ Calling list.pop() on an empty list array
- ☑ Querying split output data without length verification checks
🔍 Quick Checklist:
What is List index out of range?
The 'List index out of range' error is the standard message printed by the 'IndexError' exception class. It indicates that the numeric index passed to a list subscript (e.g. 'my_list[index]') exceeds the populated length of the list. In Python, sequences are 0-indexed; querying an index equal to or greater than the list length, or attempting to pop items from an empty list, triggers this exception.
Common Causes
- Off-by-one loop boundary error: Iterating with indices that run from 1 to 'len(items)' instead of 0 to 'len(items) - 1'.
- Popping from an empty list: Calling 'list.pop()' on an array containing zero items.
- Accessing parsed CSV or regex split match values directly: Direct index access assuming matches exist when splits yield fewer items than expected.
| Cause | Frequency |
|---|---|
| Off-by-one loops boundaries index errors | ⭐⭐⭐⭐⭐ |
| Calling pop() on empty list records | ⭐⭐⭐⭐ |
| Accessing parsed columns split data directly | ⭐⭐⭐ |
Common Mistakes
- Iterating with `range(1, len(items) + 1)` and then querying `items[i]`, missing the first element (index 0) and crashing on the last limit index.
- Modifying a list length inside a loop iteration frame while accessing values using pre-calculated index counters.
How to Fix
Python Operations & Verification
Write a helper function to retrieve list elements safely with custom fallbacks on out-of-bounds queries.
def safe_get(target_list, index, default=None):
# Support negative index mapping checks
adjusted_index = index if index >= 0 else len(target_list) + index
if 0 <= adjusted_index < len(target_list):
return target_list[index]
return default
items = [10, 20, 30]
print(safe_get(items, 3, "Missing")) # MissingPlatform Specific Fixes
Test pop operations on empty sequences in interactive console.
python3 -c "items = []; print(items.pop() if items else 'Empty')"Best Practices
- Prefer direct loop variables maps (`for item in items:`) to automate index pointer movements.
- Utilize `enumerate(items)` if both loop index and item references are required simultaneously.
Frequently Asked Questions (FAQ)
Q: What causes 'list index out of range'?
It occurs when you request an index number that is greater than or equal to the length of the list, or less than the negative length of the list.
Q: How do I safely get the last item of a list?
Use index '-1': 'last_item = my_list[-1]'. If the list might be empty, wrap it: 'last_item = my_list[-1] if my_list else None'.
Q: Why does 'range(len(my_list))' prevent this error?
Because 'range(N)' generates numbers from 0 up to 'N - 1'. This matches Python's 0-based indexing limits exactly, preventing index overflow crashes.
Q: How do I write a safe list getter?
You can write a helper function or wrapper: 'def safe_get(lst, idx, default=None): return lst[idx] if 0 <= idx < len(lst) else default'.