The List index out of range the error occurs in Python when you try to access an index outside the valid range of indices for a list. The valid range of indices for a list starts at 0 and ends at the length of the list minus 1. This error typically happens when you use an index that is greater than or equal to the length of the list. Here are a few examples of situations where you may encounter this error.
You can avoid list index out of range in Python using many ways, for example, by using using the len() function, while loop, and try-except block. In this article, I will explain how to get IndexError and how to handle it with examples.
1. Quick Examples of Handling List Index Out of Range
If you are in a hurry, below are some quick examples of avoiding list index out of range.
# Quick examples of handling list index out of range
# Example 1: Accessing an element
# Beyond the list length
mylist = [2, 4, 6]
result = mylist[5]
# Example 2: Accessing a negative index
# Beyond the list length
mylist = [2, 4, 6]
result = mylist[-5]
# Example 3: Accessing an index
# Empty list
mylist = []
result = mylist[0]
# Example 4: List index out of range
# Using while loop
mylist = [‘Python’, ‘Spark’, ‘Hadoop’]
i=0
while i <= len(mylist):
print(mylist[i])
i += 1
# Example 5: Get IndexError in for loop with range()
for i in range(4):
print(mylist[i])
# Fix the IndexError
# Example 6: Fix List index out of range
# using for loop with len()
for i in range(len(mylist)):
print(mylist[i])
# Example 7: Fix IndexError using while loop
print(“Given list:”, mylist)
i=0
while i < len(mylist):
print(mylist[i])
i += 1
# Example 8: Handle IndexError using Try Except block
# Initialize list
mylist = [‘Python’, ‘Spark’, ‘Hadoop’]
print(“Given list:”, mylist)
try:
print(mylist[5])
except IndexError:
print(“Index is out of range”)
# Example 9: String IndexError:
# List index out of range
mystring = “Sparkbyexample”
result = mystring[20]
2. The Reasons for Raising IndexError
2.1 Accessing an Element Beyond the List Length
You can get IndexError as a list index out of range to access an element beyond the length of a list. For example, mylist contains three elements 2, 4, and 6. The indices of these elements are 0, 1, and 2 respectively. When you try to access it, it raises an IndexError with the message “list index out of range“. The length of the list is 3. Here, you are attempting to access an element beyond the length of the list. The valid indices range from 0 to 2.
# Initialize the list
mylist = [2, 4, 6]
# Accessing an element
# beyond the list length
result = mylist[5]
print(result)
Yields below output.
2.2 Accessing Negative Index Beyond the List Length
You can also get the IndexError when accessing a negative index beyond the length of a list. For example, mylist contains three elements 2, 4, and 6. When you use a negative index, it counts from the end of the list. So, -1 represents the last element, -2 represents the second-to-last element.
In this program, -5 is beyond the length of the list. Since the list only has three elements, using a negative index -5 exceeds the valid range of indices. As a result, it raises an IndexError with the message “list index out of range“.
# Initialize the list
mylist = [2, 4, 6]
# Access a negative index
# Beyond the list length
result = mylist[-5]
print(result)
Yields the same output as above.
2.3 Accessing an Index in an Empty List
The IndexError can be raised when accessing an index in an empty list. For example, mylist is an empty list with no elements. When you try to access an index, such as mylist[0], it raises an IndexError with the message “list index out of range“.
An empty list has no elements, so there are no valid indices to access. Attempting to access an index in an empty list will result in an IndexError because there are no elements available at any index.
# Initialize list
mylist = []
# Accessing an index
# Empty list
result = mylist[0]
print(result)
Yields the same output as above.
2.4 Get IndexError using For Loop & range()
You can get IndexError when you access an element in a list using for loop and range() function. By default range() function returns a sequence of numbers from 0 to before the specified end number. You can iterate a range of numbers using for loop. For every iteration to access the list element using an index.
When you try to access the list element with a specified number of the range() function which does not exist in the list, IndexError will be raised as list index out of range. Since the range() function starts 0 and ends before the specified end number.
In this example, a specified number of range() function is 4, hence loop starts from 0 and ends with 3.
# Initialize the list
mylist = [‘Python’, ‘Spark’, ‘Hadoop’]
# Get IndexError in for loop with range()
for i in range(4):
print(mylist[i])
Yields the same output as above.
You can fix IndexError in the above code using the len() function.
3. How to Fix IndexError(List Index Out of Range)
Below are some ways to handle the IndexError message i.e. list index out of range.
3.1 Fix IndexError using range() & len()
You can fix IndexError using range() function with len() function in a for loop. When you access list elements using range() function in a for loop you can specify the length of the range with len(mylist) to avoid IndexError message as list index out of range.
Let’s specify the list length with the len() function to avoid IndexError.
# Initialize list
mylist = [‘Python’, ‘Spark’, ‘Hadoop’]
# Fix List index out of range
# using for loop with len()
for i in range(len(mylist)):
print(mylist[i])
Yields below output.
Fix IndexError(List Index Out of Range) Using While Loop
You can also use a while loop to fix the IndexError.When iterating over the list to access the list elements using a while loop, there is a small issue with the loop condition that leads to a “List index out of range” error.
# Initialization list
mylist = [‘Python’, ‘Spark’, ‘Hadoop’]
# Get IndexError
# Using while loop
i=0
while i <= len(mylist):
print(mylist[i])
i += 1
# Output:
# IndexError: list index out of range
To fix the error, you need to adjust the condition in the while loop to stop when the index reaches the length of the list.
In the below example, the loop condition i<len(mylist) ensures that the loop iterates as long as the index i is less than the length of mylist. By using < instead of <=, the loop stops before the index becomes equal to the length of the list. This prevents the “List index out of range” error.
# Fix IndexError using while loop
print(“Given list:”, mylist)
i=0
while i < len(mylist):
print(mylist[i])
i += 1
# Output:
# Given list: [‘Python’, ‘Spark’, ‘Hadoop’]
# Python
# Spark
# Hadoop
3.2 Avoid IndexError using Try Except block
You can use a try–except block to handle the IndexError. Let’s use a try-except block to overcome the IndexError Message as the list index out of range.
# Handle IndexError using Try Except block
# Initialize list
mylist = [‘Python’, ‘Spark’, ‘Hadoop’]
print(“Given list:”, mylist)
try:
print(mylist[5])
except IndexError:
print(“Index is out of range”)
# Output:
# Given list: [‘Python’, ‘Spark’, ‘Hadoop’]
# Index is out of range
4. String IndexError: List Index Out of Range
You can also get the error message “IndexError: string index out of range” which obtains, to access an index in a string, not a list. However, strings in Python can be treated like lists of characters, where each character corresponds to an index position.
In the below example, mystring is a string with the value “Sparkbyexample“. Each character in the string can be accessed using an index. The indices of this string range from 0 to 13 since it contains 14 characters. However, when you try to access mystring[20], you are attempting to access an index beyond the valid range of indices. Hence, it raises an IndexError with the message “string index out of range“.
# String IndexError:
# List index out of range
mystring = “Sparkbyexample”
result = mystring[20]
print(result)
Yields below output.
Conclusion
In this article, I have explained how to get the IndexError message as a list index out of range and how to handle it by using the len() function, while loop, and try–except block. Also, learning the list length before performing operations or accessing elements using indexes can help prevent the “List Index Out of Range” error.
Happy Learning !!
The List index out of range the error occurs in Python when you try to access an index outside the valid range of indices for a list. The valid range of indices for a list starts at 0 and ends at the length of the list minus 1. This error typically happens when you use Read More Python, Python Tutorial, Python List Examples