
Ask a 3-item Python list for item #3, and your script will crash on the spot. Because Python lists are zero-indexed—counting from 0, 1, 2—the highest valid index is always len(my_list) - 1.
Reaching past that boundary (or trying to grab [0] from a list that came back completely empty) triggers IndexError: list index out of range because there is no item at that position.
Visualizing Zero-Indexed Math
data = ["Apple", "Banana", "Cherry"] # Length: 3 items # Index: 0 1 2 print(data[2]) # Valid: Prints "Cherry" print(data[3]) # IndexError: slot 3 does not exist
Reading the IndexError Traceback
Read the traceback from the bottom up. Python points to the exact line where you attempted the invalid lookup.
(Note: Starting in Python 3.11+, the traceback includes fine-grained error locations. If you trigger this error, Python will draw ~~~~^^^ carets directly underneath the specific brackets that failed).
Traceback (most recent call last):
File "/var/www/app/main.py", line 2, in <module>
print(data[3])
~~~~^^^
IndexError: list index out of rangeTested Environment: Python 3.10.16 (Linux) with NumPy and Pandas | Python 3.11+ carets and Polars 2.0.0 rows noted; not run.
Part of: The Ultimate Python Debugging Guide
⚡ The Quick Fix: Compare Your Requested Index Against len()
If your code crashed, it means your requested index is mathematically greater than or equal to the total length of the list.
The Diagnostic: Insert a print statement directly above the crash to expose the invisible math.
print(f"List Length: {len(data)} | Requested Index: {i}")- If
List Lengthis0, your list is entirely empty. You cannot index an empty list. - If
List Lengthequals yourRequested Index(e.g., Length is 3, Index is 3), you forgot that Python starts counting at 0. Subtract 1 from your index.
Table of contents
- Visualizing Zero-Indexed Math
- Reading the IndexError Traceback
- ⚡ The Quick Fix: Compare Your Requested Index Against len()
- Common Causes of IndexError
- IndexError After Modifying a List Inside a Loop
- List, String, Tuple, Pandas, and Polars Error Variants
- Stop IndexErrors with enumerate() and Linters
- Worked Example: Empty Function Returns (Selenium/OS/DB)
- Frequently Asked Questions
- Official Documentation & Related Fixes
Common Causes of IndexError
This runtime exception usually indicates a logic flaw in your math or an unexpected change in your data pipeline. Here are the five most common triggers.
1. The Off-By-One Loop Trap
The most frequent cause of an IndexError is using a while loop and accidentally using <= (less than or equal to) instead of < (strictly less than) when comparing against the list length.
- The Trigger:
items = ["a", "b"]
i = 0
# Fails: When i becomes 2, items[2] crashes because the list only goes up to 1
while i <= len(items):
print(items[i])
i += 1- The Fix: Change the condition to
while i < len(items):.
2. The Look-Ahead Neighbor Comparison (i + 1)
When iterating through a list, developers often check the current item against the next item. On the final loop iteration, looking ahead requests an index that doesn’t exist.
- The Trigger:
nums = [10, 20, 30]
for i in range(len(nums)):
# Fails on the last iteration when i=2, because i+1 is 3
if nums[i] == nums[i + 1]:
print("Match!")- The Fix: Stop the loop one iteration early by using
range(len(nums) - 1), or use the Pythonic zip method to pair neighbors:for current, next_item in zip(nums, nums[1:]):.
3. .split() Returned Fewer Parts
If you use .split() to divide a string into a list, but the delimiter character doesn’t exist in the string, .split() returns a list with only one item. If you immediately try to access the second item, you crash.
- The Trigger:
text = "no-delimiter-here"
# Fails: split(',') returns ["no-delimiter-here"] (Length 1). Index 1 doesn't exist.
part = text.split(',')[1]The Fix: Always separate the split from the lookup and check the resulting length first:
parts = text.split(',')
if len(parts) > 1:
part = parts[1]- Alternatively, if you are strictly splitting a two-part string, use the
.partition()method.text.partition(',')[2]always returns exactly three parts; if the delimiter is missing, it safely hides the failure by returning an empty string (which is fine if that’s what you want).
4. The Missing Command Line Argument (sys.argv)
If you write a script that expects the user to pass a file name in the terminal, Python stores those arguments in the sys.argv list. If the user forgets to type the argument, the list is shorter than you expect.
- The Trigger:
import sys # Fails if the user just ran `python script.py` without adding a file name filename = sys.argv[1]
- The Fix: Always verify
if len(sys.argv) < 2:before accessing the list.
5. The Negative Indexing Overshoot
Python allows negative indexing to grab items from the end of a list (-1 is the last item, -2 is the second to last). However, if you count too far backward, you will overshoot the start of the list.
- The Trigger:
data = [10, 20, 30] print(data[-4]) # Fails: The list only goes back to -3
- The Fix: Ensure your negative index absolute value is less than or equal to
len(data).
IndexError After Modifying a List Inside a Loop
Sometimes you will hit an IndexError inside a for loop that looks mathematically perfect when it starts.
data = [10, 20, 30]
for i in range(len(data)):
if data[i] == 20: # Crashes on the final iteration!
data.pop(i)Why it happens: When you .pop() or .remove() an item from a list, the list instantly shrinks. The length becomes 2. But your range() function already locked in the number 3 when the loop started. On the final iteration, i becomes 2, but the list only has indices 0 and 1 left.
The Fix: Never modify a list while iterating over it by index. Iterate over a .copy() of the items themselves:
for x in data.copy():
if x == 20:
data.remove(x)(Better yet, use a list comprehension: data = [x for x in data if x != 20]).
List, String, Tuple, Pandas, and Polars Error Variants
Because lists, strings, and tuples all rely on integer indexing, they share this exact behavior. However, the error message changes slightly based on the data structure or the Data Science library you are using.
| Error Message | Context & Fix |
list index out of range | The standard error for reading an empty or out-of-bounds list. |
list assignment index out of range | You tried to assign data to an empty slot (e.g., items[0] = x on an empty list). Use items.append(x) instead. |
pop from empty list | You ran items.pop() on a list that has no elements left. Check if items: first. |
string index out of range | You asked for a character position that exceeds the string’s length. |
tuple index out of range | Same logic as lists, but for immutable tuples. |
single positional indexer is out-of-bounds | Pandas: You requested a row via df.iloc[x] that exceeds the DataFrame length. |
index x is out of bounds for axis 0 with size y | NumPy: You asked for an index outside the boundaries of a NumPy array axis. |
too many indices for array | NumPy: You tried to access a 1D array like a 2D matrix (e.g., arr[1, 2]). |
index x is out of bounds for DataFrame of height y | Polars 2.0.0 (Not run by me): You requested a row index that exceeds the DataFrame height using df[x]. |
OutOfBoundsError | Polars 2.0.0 (Not run by me): Thrown when fetching a specific row via df.row(x). Note: This is not a subclass of IndexError, so except IndexError: will not catch it. |
Stop IndexErrors with enumerate() and Linters
In Python, iterating over a list using range(len(my_list)) is considered an “anti-pattern” because it unnecessarily opens the door to IndexErrors and is difficult to read.
The Prevention: Use the built-in enumerate() function. It automatically pairs the index with the item, removing the loop off-by-one risk entirely.
# Unsafe and un-Pythonic
for i in range(len(users)):
print(i, users[i])
# Safe and Pythonic
for index, user in enumerate(users):
print(index, user)Linter Rule: If you use a modern linter, enable Pylint’s C0200 (consider-using-enumerate). It will explicitly flag range(len()) in your CI/CD pipeline and force your developers to write safer code.
Worked Example: Empty Function Returns (Selenium/OS/DB)
Let’s look at a real-world scenario where dynamic external data causes a crash.
Functions that search for data (like Selenium’s find_elements, Python’s re.findall(), glob.glob(), os.listdir(), or a SQL database .fetchall()) rarely throw an error if they find nothing. They simply return an empty list [].
The Code:
from selenium.webdriver.common.by import By # The developer assumes the price tag is always present in the DOM elements = driver.find_elements(By.CLASS_NAME, "price") # Extract the text from the first match final_price = elements[0].text
The Traceback (Excerpt):
Traceback (most recent call last):
...
final_price = elements[0].text
~~~~~~~~^^^
IndexError: list index out of rangeThe Thought Process & Fix:
- Python crashed on
elements[0]. - The developer knows
0is a valid index for any normal list, so the list must be completely empty. - Why is it empty? If the page hasn’t loaded yet, Selenium returns an empty list immediately.
- The Result: The developer replaces the immediate list lookup with an Explicit Wait (
WebDriverWait), halting execution until the elements actually exist in the DOM.
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
elements = WebDriverWait(driver, 10).until(
EC.presence_of_all_elements_located((By.CLASS_NAME, "price"))
)
final_price = elements[0].textFrequently Asked Questions
try/except block to catch an IndexError?Yes. In Python, this is called EAFP (“Easier to Ask for Forgiveness than Permission”). It is highly Pythonic to attempt the extraction and handle the fallback if it fails.try:<br>first_item = my_list[0]<br>except IndexError:<br>first_item = "Default Value"
However, beware of the pass trap. If you handle the exception by simply passing, but forget to define your fallback variable, you will instantly trigger a secondary error when you try to use the undefined variable later.<code>try:<br>first_item = my_list[0]<br>except IndexError:<br>pass # Bad practice!<br>print(first_item) # NameError (or UnboundLocalError if inside a function)
Unlike Python dictionaries, which have a safe .get(key, default) method, lists do not have a built-in safe getter. The cleanest way to pull the first item without crashing is to check if the list exists inline:Unsafe: Crashes if empty<br>first = my_list[0]<br>Safe: Returns "Default" if the list is empty<br>first = my_list[0] if my_list else "Default"
Yes. Because strings and tuples are ordered sequences just like lists, attempting to retrieve my_string[50] on a 10-character string will result in an IndexError: string index out of range.
You use an integer (a number) to look up items in a list, resulting in an IndexError if the math is wrong. You use a key to look up items in a dictionary, resulting in a KeyError if that key does not exist.
Official Documentation & Related Fixes
- Master Guide: The Ultimate Python Debugging Guide: Tracebacks, Exceptions, and Fixes
- Related Error: How to Fix NameError: name ‘x’ is not defined
- Official Python Docs: Python Exceptions – IndexError

