Submitting the form below will ensure a prompt response from us.
This error occurs when trying to access a list index that doesn’t exist.
📌 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
📌 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])
📌 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")
📌 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")
📌 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")
✔ 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.
Submitting the form below will ensure a prompt response from us.