error python

Python IndexError

Understanding Python IndexError - raised when a sequence index is out of range, such as accessing a list element that doesn't exist.

What It Means

IndexError is raised when you try to access an index in a sequence (list, tuple, string) that doesn’t exist. The most common form is: IndexError: list index out of range. This means you’re trying to access an element at a position beyond the length of the sequence.

Common Causes

  • Accessing an empty list (my_list[0] when list is empty)
  • Off-by-one errors (using len(list) as an index instead of len(list) - 1)
  • Loop index exceeds list length
  • Assuming a function returns a list with items when it returns an empty list
  • Popping from an empty list
  • Negative indices exceeding the list length

How to Fix

Check length before accessing

my_list = []

# Bad: accessing empty list
first = my_list[0]  # IndexError!

# Good: check first
if len(my_list) > 0:
    first = my_list[0]

# Or use a default
first = my_list[0] if my_list else None

Fix off-by-one errors

my_list = [1, 2, 3]

# Bad: index 3 doesn't exist (valid indices are 0, 1, 2)
last = my_list[len(my_list)]  # IndexError!

# Good: use -1 for the last element
last = my_list[-1]  # 3

# Good: subtract 1 from length
last = my_list[len(my_list) - 1]  # 3

Safe list access with try/except

def safe_get(lst, index, default=None):
    try:
        return lst[index]
    except IndexError:
        return default

my_list = [1, 2, 3]
value = safe_get(my_list, 10, default=0)  # Returns 0
my_list = [1, 2, 3]

# Bad: accessing i+1 without bounds checking
for i in range(len(my_list)):
    print(my_list[i], my_list[i + 1])  # IndexError on last iteration!

# Good: stop one element early
for i in range(len(my_list) - 1):
    print(my_list[i], my_list[i + 1])

# Good: use zip for pairs
for a, b in zip(my_list, my_list[1:]):
    print(a, b)

# Best: iterate directly instead of using indices
for item in my_list:
    print(item)

Fix pop from empty list

# Bad: popping from empty list
my_list = []
item = my_list.pop()  # IndexError!

# Good: check first
if my_list:
    item = my_list.pop()

# Or use a try/except
try:
    item = my_list.pop()
except IndexError:
    item = None

Fix string index errors

text = "hello"

# Bad: index beyond string length
char = text[10]  # IndexError!

# Good: check length
if len(text) > 10:
    char = text[10]

# Slicing never raises IndexError (returns empty string)
chars = text[10:20]  # Returns "" instead of raising error

Fix with regex/split results

# Common: split returns fewer items than expected
line = "name,age"
parts = line.split(",")
# parts = ["name", "age"]
value = parts[2]  # IndexError!

# Fix: check the number of parts
parts = line.split(",")
if len(parts) >= 3:
    value = parts[2]
else:
    value = None
  • Python KeyError - Missing dictionary key (the dict equivalent of IndexError).
  • Python TypeError - Using an invalid type as an index (e.g., list["key"]).
  • Python ValueError - Value-related errors like list.remove(x) when x is not in the list.