How to Fix IndexError list index out of range in Python With Examples

 

What Is IndexError?

IndexError: list index out of range occurs when you try to access an element in a list using an index that doesn't exist. Python indices start from 0.

Common Scenarios & Fixes

1. Accessing Non-Existing Index

Incorrect:

fruits = ["apple", "orange", "mango"]
print(fruits[3])

Fix:

print(fruits[2])

2. Accessing Index in Empty List

Incorrect:

data = []
print(data[0])

Fix:

if data:
    print(data[0])
else:
    print("List is empty")

3. Loop Exceeds List Length

Incorrect:

nums = [10, 20, 30]
for i in range(4):
    print(nums[i])

Fix:

for i in range(len(nums)):
    print(nums[i])

Or:

for num in nums:
    print(num)

4. Invalid Negative Index

Incorrect:

data = [100, 200]
print(data[-3])

Fix:
Valid negative indices: -1 (last), -2 (second last)

Pro Tips:

  • Always use len() to check bounds.
  • Use try-except to catch and handle errors.
  • Iterate directly over the list when possible.

0 Comments:

Post a Comment