Get in Touch With Us

Submitting the form below will ensure a prompt response from us.

IndexError: List Index Out of Range – Causes & Fixes

This error occurs when trying to access a list index that doesn’t exist.

βœ… Common Causes & Solutions

Accessing an Invalid Index

πŸ“Œ Cause: Index is out of the valid range of the list.
βœ… Fix: Check the list length before accessing an index.

❌ Wrong Example

numbers = [10, 20, 30]
print(numbers[3])  # IndexError! No element at index 3

βœ… Corrected Code

numbers = [10, 20, 30]
if len(numbers) > 2:  # Check before accessing
    print(numbers[2])  # Safe access

Iterating Past the List Size

πŸ“Œ Cause: Loop goes beyond list length.
βœ… Fix: Use len() to avoid out-of-range errors.

❌ Wrong Example

fruits = ["apple", "banana"]
for i in range(3):  # Index 2 does not exist
    print(fruits[i])

βœ… Corrected Code

fruits = ["apple", "banana"]
for i in range(len(fruits)):  # Iterate safely
    print(fruits[i])

Accessing Empty List

πŸ“Œ Cause: Trying to access an element in an empty list.
βœ… Fix: Check if the list is empty before accessing elements.

❌ Wrong Example

data = []
print(data[0])  # IndexError! No elements in the list

βœ… Corrected Code

data = []
if data:  # Check if the list is not empty
    print(data[0])
else:
    print("List is empty")

Using Wrong Index with split()

πŸ“Œ Cause: split() may return fewer elements than expected.
βœ… Fix: Use try-except or len() to handle missing elements.

❌ Wrong Example

text = "hello"
words = text.split()  # ['hello']
print(words[1])  # IndexError!

βœ… Corrected Code

text = "hello"
words = text.split()

if len(words) > 1:
    print(words[1])
else:
    print("Not enough words")

Negative Index Out of Range

πŸ“Œ Cause: Using a negative index beyond list bounds.
βœ… Fix: Ensure the index is within the list size.

❌ Wrong Example

nums = [1, 2, 3]
print(nums[-4])  # IndexError! Only -1, -2, -3 are valid

βœ… Corrected Code

nums = [1, 2, 3]
if abs(-4) <= len(nums):
    print(nums[-4])
else:
    print("Index out of range")

πŸ”₯ Quick Fixes Summary

βœ” Check list length before accessing an index.
βœ” Use if len(list) > index: to prevent errors.
βœ” Avoid empty lists by verifying with if list:.
βœ” Use try-except IndexError for handling dynamic lists.

About Author

Jayanti Katariya is the CEO of Moon Technolabs, a fast-growing IT solutions provider, with 18+ years of experience in the industry. Passionate about developing creative apps from a young age, he pursued an engineering degree to further this interest. Under his leadership, Moon Technolabs has helped numerous brands establish their online presence and he has also launched an invoicing software that assists businesses to streamline their financial operations.

Related Q&A