Python index out exception

Python List Index Out Of Range: Error and Resolution

Hello coders!! In this article, we will learn about python list index out of range error and will also learn how to resolve such errors. At first, we should understand what does this means?

Python list index out of range arises when we try to access an invalid index in our Python list. In Python, lists can be initialized without mentioning the length of the list. This feature allows the users to add as much data to the list without encountering errors. But when accessing the data, you have to keep track of its index.

If you try to access the list index out of its range, it’ll throw an IndexError. Now, let us look into this topic deeply to have a better understanding.

What is IndexError Python List Index Out Of Range?

IndexError occurs when there is an invalid index passed to access the elements of the object. In python, the index starts from 0 and ranges till the length-1 of the list. Whenever the element is accessed from the list by using the square brackets, the __getitem__ method is called. This method first checks if the index is valid. The index cannot be float, or greater than or equal to the length of the list.

So, whenever you try to access the element which is not acceptable, IndexError is thrown. In our case, the index is out of the range, which means it’s greater than or equal to the length of the list. This error also applies to the indexing greater than the length of the string.

Causes of IndexError Python List Index Out Of Range?

There are several causes for this error to appear. Most of the causes are raised because the programmers assume that the list index starts from 1.

In Python, the list index begins from 0. Unfortunately, programmers who come from Lua, Julia, Fortran, or Matlab, are used to index the items from 1. In such cases, this error occurs.

There are many other scenarios where this error is raised, following are the examples of it –

Example 1: Python list index out of range with len()

Output:

Explanation:

In this code snippet, we have created a list called color having four elements – red, blue, green, pink

In python, the indexing of the elements in a list starts from 0. So, the corresponding index of the elements are:

The length of the list is 4. So, when we try to access color[len(color)], we are accessing the element color[4], which does not exist and goes beyond the range of the list. As a result, the list index out of bounds error is displayed.

READ  Warface ошибка загрузки данных игрока

Example 2: Python list index out of range in loop

Explanation:

Here, the list lst contains the value 1,2,3,4 having index 0,1,2,3 respectively.

When the loop iterates, the value of i is equal to the element and not its index.

So, when the value of i is 1( i.e. the first element), it displays the value x[1] which is 2 and so on.

But when the value of i becomes 4, it tries to access the index 4, i.e. x[4], which becomes out of bound, thus displaying the error message.

Example 3: Case where your list length changes

Output:

Explanation:

In the above example, the user wants to remove the element if it matches a certain value. But the problem, in this case, is that while iterating, the length of your list is changing. So, when you reach the 6th iteration, the lst[6]==4 will throw an error because there is no 6th element in the list. When the two elements (4s) are removed the length of the list is reduced.

Solution for IndexError python list index out of range Error

The best way to avoid this problem is to use the len(list)-1 format to limit the indexation limits. This way you can not only avoid the indexing problems but also make your program more dynamic.

1. Lists are indexed from zero:

We need to remember that indexing in a python list starts from 0 and not 1. So, if we want to access the last element of a list, the statement should be written as lst[len-1] and not lst[len], where len is the number of elements present in the list.

So, the first example can be corrected as follows:

Output:

Explanation:

Now that we have used color[len(color)-1], it accesses the element color[3], which is the last element of the list. So, the output is displayed without any error.

2. Use range() in loop:

When one is iterating through a list of numbers, then range() must be used to access the elements’ index. We one forgets to use it, instead of index, the element itself is accessed, which may give a list index out of range error.

So, in order to resolve the error of the second example, we have to do the following code:

Output:

Explanation:

Now, that we have used the range() function from 0 to the length of the list, instead of directly accessing the elements of the list, we access the index of the list, thus avoiding any sort of error.

3. Avoiding pop() while iterating through the list

Code:

Output:

Explanation:

You can use the pop() function in a loop to remove the items from the list, but if you use the same list to change and iterate it’ll through an error. As an alternative to this, you can use the list comprehension along with an inline if to avoid adding elements to the list.

4. Avoiding remove() while iterating through the list

Code:

Output:

Explanation:

In the above code, the user intends to remove all the occurrences of 4 from the list. But while iterating through the loop, the remove() function reduces its length. This causes an indexation error in lst[i]. As an alternative, you can use the range() function to use the remove() function a limited number of times. The count() function is amazingly helpful to avoid tedious loop errors.

5. Properly using While Loop

Code:

Output:

Explanation:

Iterating through a while loop can be tricky sometimes. We first have declared the list with random elements and a variable with an integer value of 0. This is because the indexing starts from 0 in Python.

In the condition for the while loop, we’ve stated that the value of the index should be always less than the length of the list. Then we increment the value of the index by 1 in every loop. This creates perfect sync between the 0 and maximum value of the index to avoid any IndexErrors.

READ  No physical disk error

6+. Properly using For Loop

Code:

Output:

Explanation:

Creating a proper for loop is an easy task, especially in python. Use the range() function to iterate the value from 0 to length-1 and close the loop thereafter.

Python List Index Out of Range Try Except

Exceptions are a great way of knowing what error you encounter in the program. Moreover, you can use the try-except blocks to avoid these errors explicitly. The following example will help you to understand –

Code:

Output:

Explanation:

In the above example, the value of ‘i’ ranges from 0 to the length of the list. At the very end of its value, it’ll throw IndexError because the index exceeds the maximum value. As a result, we’ve placed it inside the try block to make sure that we can handle the exception. Then we created an except block which prints whenever an exception is raised. The output can help you understand that the code breaks at its last iteration.

Need a Default Value instead of List Index Out of Range?

Sometimes, we need to initialize variables in such a way that, if an error is raised it’ll get assigned to the default value. This declaration can be achieved by using a try-except block or if statement. The following code will help you understand –

Code:

Output:

Explanation:

Case 1, uses the try-except IndexError block to declare the value. As we have used [3] in the index and the length of the list is 2, it’ll execute the except block.

Case 2 uses a simple inline if statement which declares the value if the index is greater than the length of the list.

Must Read:

Conclusion: Python List Index Out of Range

In day to day programming, list index out of range error is very common. We must make sure that we stay within the range of our list in order to avoid this problem. To avoid it we must check the length of the list and code accordingly.

However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

Источник

List Index Out of Range – Python Error [Solved]

In this article, we’ll talk about the IndexError: list index out of range error in Python.

In each section of the article, I’ll highlight a possible cause for the error and how to fix it.

You may get the IndexError: list index out of range error for the following reasons:

  • Trying to access an index that doesn’t exist in a list.
  • Using invalid indexes in your loops.
  • Specifying a range that exceeds the indexes in a list when using the range() function.

Before we proceed to fixing the error, let’s discuss how indexing work in Python lists. You can skip the next section if you already know how indexing works.

How Does Indexing Work in Python Lists?

Each item in a Python list can be assessed using its index number. The first item in a list has an index of zero.

Consider the list below:

In the example above, we have a list called languages . The list has three items — ‘Python’, ‘JavaScript’, and ‘Java’.

To access the second item, we used its index: languages[1] . This printed out JavaScript .

Some beginners might misunderstand this. They may assume that since the index is 1, it should be the first item.

To make it easier to understand, here’s a breakdown of the items in the list according to their indexes:

Python (item 1) => Index 0
JavaScript (item 2) => Index 1
Java (item 3) => Index 2

As you can see above, the first item has an index of 0 (because Python is «zero-indexed»). To access items in a list, you make use of their indexes.

What Will Happen If You Try to Use an Index That Is Out of Range in a Python List?

If you try to access an item in a list using an index that is out of range, you’ll get the IndexError: list index out of range error.

READ  Stalker чистое небо error cannot open file fsgame ltx

Here’s an example:

In the example above, we tried to access a fourth item using its index: languages[3] . We got the IndexError: list index out of range error because the list has no fourth item – it has only three items.

The easy fix is to always use an index that exists in a list when trying to access items in the list.

How to Fix the IndexError: list index out of range Error in Python Loops

Loops work with conditions. So, until a certain condition is met, they’ll keep running.

In the example below, we’ll try to print all the items in a list using a while loop.

The code above returns the IndexError: list index out of range error. Let’s break down the code to understand why this happened.

First, we initialized a variable i and gave it a value of 0: i = 0 .

We then gave a condition for a while loop (this is what causes the error): while i .

From the condition given, we’re saying, «this loop should keep running as long as i is less than or equal to the length of the language list».

The len() function returns the length of the list. In our case, 3 will be returned. So the condition will be this: while i . The loop will stop when i is equal to 3.

Let’s pretend to be the Python compiler. Here’s what happens as the loop runs.

Here’s the list: languages = [‘Python’, ‘JavaScript’, ‘Java’] . It has three indexes — 0, 1, and 2.

When i is 0 => Python

When i is 1 => JavaScript

When i is 2 => Java

When i is 3 => Index not found in the list. IndexError: list index out of range error thrown.

So the error is thrown when i is equal to 3 because there is no item with an index of 3 in the list.

To fix this problem, we can modify the condition of the loop by removing the equal to sign. This will stop the loop once it gets to the last index.

The condition now looks like this: while i .

The loop will stop at 2 because the condition doesn’t allow it to equate to the value returned by the len() function.

How to Fix the IndexError: list index out of range Error in When Using the range() Function in Python

By default, the range() function returns a «range» of specified numbers starting from zero.

Here’s an example of the range() function in use:

As you can see in the example above, range(5) returns 0, 1, 2, 3, 4.

You can use the range() function with a loop to print the items in a list.

The first example will show a code block that throws the IndexError: list index out of range error. After pointing out why the error occurred, we’ll fix it.

The example above prints all the items in the list along with the IndexError: list index out of range error.

We got the error because range(4) returns 0, 1, 2, 3. Our list has no index with the value of 3.

To fix this, you can modify the parameter in the range() function. A better solution is to use the length of the list as the range() function’s parameter.

The code above runs without any error because the len() function returns 3. Using that with range(3) returns 0, 1, 2 which matches the number of items in a list.

Summary

In this article, we talked about the IndexError: list index out of range error in Python.

This error generally occurs when we try to access an item in a list by using an index that doesn’t exist within the list.

We saw some examples that showed how we may get the error when working with loops, the len() function, and the range() function.

We also saw how to fix the IndexError: list index out of range error for each case.

Источник

Smartadm.ru