Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

IndexError in Python — list index out of range Fix (2026) | Tutorials Logic

What is IndexError?

An IndexError occurs in Python when you try to access an element of a sequence (list, tuple, or string) using an index that is outside the valid range. Python sequences are zero-indexed, meaning the first element is at index 0 and the last is at index len(sequence) - 1. Accessing any index beyond this range raises an IndexError.

Common Causes

  • Accessing an element from an empty list or sequence
  • Off-by-one error — using len(list) as an index instead of len(list) - 1
  • Using a hardcoded index that exceeds the actual list length
  • Looping past the end of a list with a manual index counter
  • Misunderstanding negative indexing behavior

Quick Fix (TL;DR)

Quick Solution
# ❌ Problem
items = [10, 20, 30]
print(items[3])  # IndexError: list index out of range (valid: 0, 1, 2)

# ✅ Solution
print(items[2])   # 30 — last valid index
print(items[-1])  # 30 — negative index for last element

Common Scenarios & Solutions

Scenario 1: Accessing an Empty List

Trying to access any index of an empty list raises an IndexError immediately. Always check if a list is non-empty before accessing its elements.

Problem
results = []
first = results[0]  # IndexError: list index out of range
Solution
results = []

# ✅ Check before accessing
if results:
    first = results[0]
else:
    first = None

# ✅ Or use a try/except
try:
    first = results[0]
except IndexError:
    first = None

Scenario 2: Off-by-One Error in a Loop

A classic off-by-one error occurs when using range(len(list)) but accidentally going one step too far, or when manually incrementing an index counter past the last valid position.

Problem
fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits) + 1):  # +1 causes IndexError on last iteration
    print(fruits[i])
Solution
fruits = ["apple", "banana", "cherry"]

# ✅ Best: iterate directly over the list
for fruit in fruits:
    print(fruit)

# ✅ If you need the index, use enumerate()
for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")

Scenario 3: Hardcoded Index

Using a hardcoded index assumes the list always has a certain number of elements. If the list is shorter than expected (e.g., from a filtered result or API response), the index will be out of range.

Problem
def get_top_scores(scores):
    return scores[0], scores[1], scores[2]  # IndexError if fewer than 3 scores

scores = [95, 87]
top = get_top_scores(scores)  # IndexError: list index out of range
Solution
def get_top_scores(scores, n=3):
    # ✅ Use slicing — never raises IndexError
    return scores[:n]

scores = [95, 87]
top = get_top_scores(scores)  # [95, 87] — no error

Scenario 4: Looping Past the End

When using a while loop with a manual index, it is easy to forget to stop at the right boundary. Always use while i < len(list) rather than while i <= len(list).

Problem
items = [1, 2, 3]
i = 0
while i <= len(items):  # Should be < not <=
    print(items[i])     # IndexError on last iteration when i == 3
    i += 1
Solution
items = [1, 2, 3]
i = 0
while i < len(items):  # ✅ Strict less-than
    print(items[i])
    i += 1

# ✅ Even better: use a for loop
for item in items:
    print(item)

Best Practices

  • Prefer for-in loops - Iterating directly over a list (for item in list) eliminates index-related errors entirely.
  • Use enumerate() for indexed loops - for i, item in enumerate(list) is safer than manual index management.
  • Use slicing instead of hardcoded indices - list[:3] never raises IndexError even if the list has fewer than 3 elements.
  • Check list length before access - Use if list or if len(list) > n before accessing specific indices.
  • Use negative indices carefully - list[-1] is the last element, but list[-len(list)-1] still raises IndexError.
  • Use try/except for dynamic data - When list size is unpredictable (API data, user input), wrap index access in try/except IndexError.
  • Use while i < len(list) - Always use strict less-than in while loops to avoid off-by-one errors.

Related Errors

Key Takeaways
  • IndexError occurs when you access a list, tuple, or string with an index outside the valid range.
  • Python lists are zero-indexed — valid indices are 0 to len(list)-1.
  • Use for item in list instead of index-based loops to avoid IndexError entirely.
  • Slicing (list[:n]) never raises IndexError even if the list is shorter than n.
  • Always check if a list is non-empty before accessing its first or last element.
  • Use while i < len(list) (strict less-than) in while loops to avoid off-by-one errors.

Frequently Asked Questions


Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.