Skip to content
IndexError: list index out of range

IndexError: list index out of range

DodaTech 2 min read

IndexError: list index out of range means you tried to access an element at a position that doesn’t exist in the list. Lists are zero-indexed, so a list with 3 elements has indices 0, 1, and 2 — index 3 raises this error.

What It Means

The index you provided is either too high (>= length of the list) or too low (< -length of the list, for negative indexing). Python lists don’t auto-expand when you assign to an out-of-range index — you need to append or insert instead.

Why It Happens

  • Using an index equal to or greater than len(list)
  • Off-by-one errors (forgetting zero-indexing)
  • Empty list: any index raises this error
  • Loop that goes one iteration too far
  • Assuming a list has more elements than it actually does

How to Fix It

Step 1: Check the list length before accessing

items = [10, 20, 30]

# BAD — index 3 is out of range (valid: 0, 1, 2)
print(items[3])

# GOOD — check first
if len(items) > 3:
    print(items[3])
else:
    print(f"Only {len(items)} items available")

Step 2: Fix off-by-one errors in loops

items = [10, 20, 30]

# BAD — range(1, 4) gives indices 1, 2, 3
for i in range(1, 4):
    print(items[i])

# GOOD — range(len(items)) gives 0, 1, 2
for i in range(len(items)):
    print(items[i])

# EVEN BETTER — iterate directly
for item in items:
    print(item)

Step 3: Use negative indexing safely

items = [10, 20, 30]

# BAD — empty list, no last element
empty = []
print(empty[-1])

# GOOD — check first
if empty:
    print(empty[-1])
else:
    print("List is empty")

Step 4: Use .pop() safely

items = [10, 20, 30]

# BAD — popping too many times
for _ in range(5):
    print(items.pop())

# GOOD — stop when empty
while items:
    print(items.pop())

Step 5: Validate input that generates indexes

# If user input is used as an index:
user_index = int(input("Enter index: "))
items = [10, 20, 30]

if 0 <= user_index < len(items):
    print(items[user_index])
else:
    print(f"Index must be between 0 and {len(items) - 1}")
How do I handle an IndexError gracefully?
Use try/except: try: value = items[idx] except IndexError: value = None. This pattern is common when the index comes from user input or external data that you can’t control.
Can I create a list that automatically grows when I assign to an index?
No — Python lists don’t support auto-growing on index assignment. Use list.append() for sequential growth, or pre-allocate with [None] * size if you know the final size. For sparse data, consider using a dictionary instead.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro