| by Arround The Web | No comments

List Index Out of the Range Python

The reason Python is so popular is because of its efficiency, flexibility, and a huge library. In Python, you will encounter errors and bugs similar to other programming languages. The “list index out of range” error is notoriously frequent when working with lists. It usually takes place when you try to access/call an index that doesn’t exist in a list.

The objective of this Python guide is to explain why this error occurs and how to avoid it.

What is the Python “list index out of range” Error?

The “list index out of range” is a common error that is faced when trying to access/call an index that is not within the range of a list. The following reasons usually cause this error:

  • Attempting to Access a Non-Existent Index.
  • Using a Negative Index.
  • Looping Through a List Incorrectly.

Now, let’s discuss each of the discussed reasons one by one.

Cause 1: Attempting to Access a Non-Existent Index

One of the most common causes of the error named “list index out of range” is attempting to access an index that doesn’t exist in the list.

Example
The below code scenario raises the “list index out of range” error:

my_list = [41, 22, 33]
print(my_list[3])

In the above code, the list “my_list” has three elements, and we tried to access the fourth element by using the index “3“. Since the maximum index of the list is “2“, we get the error named “list index out of range“.

Output

The above output implies that the accessed index is out of range and so the error is faced.

Cause 2: Using a Negative Index

Another common cause of the “list index out of range” error is using a negative index. In Python, you can access elements in a list using “negative indexing”. However, if you use a “negative index” that is greater than the length of the list, you will be returned with the discussed error.

Example
Let’s overview the following example that causes this error:

my_list = [12, 23, 34]
print(my_list[-4])

In the above code, we tried to access the element at index “-4“, which is outside the range of the list. Therefore, we encountered the discussed limitation.

Output

As seen, the “IndexError: list index out of range” is encountered.

Cause 3: Looping Through a List Incorrectly

Looping through a list is a common operation in Python programming. However, if you’re not careful, you may encounter the “list index out of range” error.

Example
Let’s go through the following example code:

my_list = [41, 32, 23, 54, 35]
for i in range(len(my_list)+1):
  print(my_list[i])

In the above lines of code, the “for” loop is used to iterate through the given list and access all its elements. The “list index out of range” error is displayed when the loop exceeds its last iteration via “+1”.

Output

Based on the above output, it can be analyzed that the error arises when the loop iterates over the last list element.

How to Fix the Python Error “list index out of range”?

To fix the discussed error, different solutions are utilized in Python. Some of the solutions are listed below:

  • Check the Length of the List.
  • Use “try/except” Blocks.
  • Avoid Using Negative Indices.
  • Modifying the Loop to Avoid the Error.

Solution 1: Check the Length of the List
Before accessing an index of a list, it’s important to check the list length to ensure that the index is within the list’s range.

Example
Have a look at the below-provided example:

my_list = [41, 42, 33, 54, 15]
if len(my_list) > 4:
  print(my_list[4])
else:
  print("Index doesn't exist in the list")

In the above code block, the “len()” function is utilized along with the “if” statement to check the length of the given list. If the length of the given list is within the accessing element range, then we can safely access the element without encountering the “list index out of range” error.

Output

Based on the above output, it can be seen that the value of the list at index “4” i.e., “15” is accessed appropriately.

Solution 2: Use “try/except” Blocks
Another way to handle the “list index out of range” error is by using “try/except” blocks. A “try” block executes code and the faced errors are caught via the “except” block, which effectively handles them.

Example
Here is an example code:

my_list = [14, 24, 35]
try:
  print(my_list[3])
except IndexError:
  print("Index out of range")

In the above code snippet, the index value present at position “3” is accessed inside the “try” block. If the length of the list is out of range, then the “except” block executes the code and displays the error message instead, thereby avoiding the limitation.

Output

The above output shows that the accessing value is out of the range according to the given list but the error is taken care of.

Solution 3: Avoid Using Negative Indices
Using negative indices can sometimes cause confusion and lead to errors. It’s recommended to use positive indices when accessing elements of a list.

Example
Let’s overview the following example code:

my_list = [12, 32, 53, 56, 66]
if len(my_list) > 3:
  print(my_list[4])
else:
  print("Index out of range")

In this code, the “4th” element of the given list is accessed using a positive index i.e., “4” instead of a negative index.

Output

Solution 4: Modifying the Loop to Avoid the Error
To avoid the discussed error when looping through a list, you can modify the loop to avoid accessing non-existent indexes.

Example
The following example explains the stated concept:

my_list = [21, 32, 43, 54, 45]
for i in range(len(my_list)):
  if i < len(my_list):
    print(my_list[i])
  else:
    print("Index doesn't exist in the list")

The above code block defines a list of integers and prints each value in the list by looping through its indices. After that, the “if/else” statement is used to check for indices outside the bounds of the list by placing an exception.

Conclusion

In Python, the “list index out of range” is a familiar error that happens when trying to access an index outside of the list’s range. There are several causes of this error, including attempting to access a non-existent index, using a negative index, or looping through a list incorrectly. To resolve this error, you can check the length of the list, use “try/except” blocks or avoid using negative indices.

Share Button

Source: linuxhint.com

Leave a Reply