A Python list index out of range error stopped a client’s nightly sales report last month. The list had three prices; the loop asked for a fourth.
Wrapping the loop in try hides the crash, but the total is still wrong, so I fix the index instead.
Quick answer: a list with n items only has indexes 0 to n - 1 (or -n to -1). Loop over the items directly, and check 0 <= i < len(items) before reading an index you didn’t create:
for price in prices: # no index, no IndexError
total += price
value = items[i] if 0 <= i < len(items) else None
In this tutorial, I’ll fix the Python list index out of range error for each cause I keep running into on real projects. Outputs come from Python 3.12.5.
What does IndexError: list index out of range mean?
Python raises it when items[i] points past either end of the list. Here’s a three-customer queue:
queue = ["Emily", "James", "Olivia"] # three customers -> indexes 0, 1, 2
print(len(queue), queue[0], queue[2], queue[-1])
print(queue[1:10]) # a slice never raises
print(queue[3]) # one past the end
Output:
3 Emily Olivia Olivia
['James', 'Olivia']
Traceback (most recent call last):
File "C:\pyguides\queue_index.py", line 5, in <module>
print(queue[3]) # one past the end
~~~~~^^^
IndexError: list index out of range

queue[3] stops the script with IndexError: list index out of range.The line above the error shows the failing lookup. It’s a runtime error, like the others in my overview of the types of errors in Python.
Fix the off-by-one error in a for loop
Most IndexErrors I debug come from loops that count from 1, the way you’d count on paper:
prices = [19.99, 5.49, 12.00]
total = 0
for i in range(1, len(prices) + 1): # counting items from 1
total += prices[i]
print(f"item {i}: ${prices[i]:.2f}")
print(f"Total: ${total:.2f}")
Output:
item 1: $5.49
item 2: $12.00
Traceback (most recent call last):
File "C:\pyguides\prices_loop_bug.py", line 4, in <module>
total += prices[i]
~~~~~~^^^
IndexError: list index out of range
It skipped $19.99 at index 0, printed two items, then crashed at index 3. A while i <= len(prices) loop fails the same way. Let enumerate() do the numbering instead:
prices = [19.99, 5.49, 12.00]
total = 0
for n, price in enumerate(prices, start=1): # numbers from 1, no indexing
total += price
print(f"item {n}: ${price:.2f}")
print(f"Total: ${total:.2f}")
Output:
item 1: $19.99
item 2: $5.49
item 3: $12.00
Total: $37.48

range() loop crashes after two items. Right: enumerate(prices, start=1) prints all three and a $37.48 total.start=1 only changes the label, never the lookup. More patterns are in my guides to enumerate() in Python and getting the index in a for loop.
Check for an empty list before reading the first item
A filter that matches nothing returns [], and [][0] fails even though index 0 looks safe. Here no order comes from New York:
orders = [{"customer": "Emily", "state": "TX"}, {"customer": "James", "state": "CA"}]
ny = [o for o in orders if o["state"] == "NY"]
print("NY orders:", len(ny))
first = ny[0] if ny else None # guard the empty case
print("first NY order:", first)
print("latest:", orders[-1]["customer"] if orders else None)
Output:
NY orders: 0
first NY order: None
latest: James
An empty list is falsy, so ny[0] if ny else None covers it, and the same guard protects items[-1]. Other checks are in how to check if a list is empty in Python.
Why does deleting items in a loop cause IndexError?
range(len(amounts)) is fixed when the loop starts. Each del shrinks the list, so the last indexes no longer exist:
amounts = [120.50, 0.00, 42.10, 0.00]
try:
for i in range(len(amounts)):
if amounts[i] == 0:
del amounts[i] # the list shrinks, range() doesn't
except IndexError as err:
print("del in a loop ->", err, "| left:", amounts)
amounts = [120.50, 0.00, 42.10, 0.00]
amounts = [a for a in amounts if a != 0]
print("comprehension ->", amounts)
Output:
del in a loop -> list index out of range | left: [120.5, 42.1]
comprehension -> [120.5, 42.1]

Build a new list instead. A list comprehension is the shortest way, and it never touches a stale index.
Guard list indexes from split() and user input
When the index comes from outside your code, like a CSV line or user input, check the length first:
rows = [
"2026-03-02,Emily,120.50",
"2026-03-03,James", # amount missing
"2026-03-04,Olivia,42.10",
]
for line in rows:
parts = line.split(",")
if len(parts) < 3:
print(f"skipped {line!r}: expected 3 fields, got {len(parts)}")
continue
date, name, amount = parts
print(f"{date} {name:<7} ${float(amount):.2f}")
Output:
2026-03-02 Emily $120.50
skipped '2026-03-03,James': expected 3 fields, got 2
2026-03-04 Olivia $42.10

parts[2].For a single index you got from input, check 0 <= i < len(items) first. For arrays, see checking if an array index exists in Python.
Common errors and how to fix them
| Message | Usual cause | Fix |
|---|---|---|
list index out of range | Index >= len(), or an empty list | Loop over items, guard with if items |
list assignment index out of range | Assigning past the end | Use append() instead |
string index out of range | Same bug on a string | String IndexError fix |
tuple index out of range | Unpacking or format() args | Tuple IndexError fix |
KeyError | Missing dictionary key, not an index | Dictionary KeyError fix |
Keep going with these list guides:
- Get the index of an element in a Python list
- Find the size of a Python list
- Slice lists in Python
- The Python list pop() method
Frequently asked questions
What causes IndexError: list index out of range in Python?
An index of len(items) or more, below -len(items), or any index on an empty list.
How do I fix list index out of range in a for loop?
Loop over the items directly or use enumerate(). With range(), stop at len(items).
How do I check if a list index exists in Python?
Use -len(items) <= i < len(items), or 0 <= i < len(items) if negative indexes aren’t allowed.
Does slicing raise IndexError?
No. A slice past the end just returns a shorter or empty list.
Should you catch IndexError with try and except?
Only when a missing item is expected, like an optional column. Fix the index for loop bugs.
Where is IndexError documented?
See IndexError in the Python docs.

Bijay Kumar is a 13-time Microsoft MVP with more than 18 years in software development, and the founder of Python Guides and TSinfo Technologies. He started out building .NET and SharePoint solutions at HP, TCS and KPIT before moving into Python, machine learning and AI, and he also builds web apps with TypeScript and React. He writes the tutorials here himself, and every example is run before publishing so you see the real output. More about Bijay · Microsoft MVP profile · LinkedIn