Indexerror list index out of range python ошибка

Цель создания данного вопроса и ответа к нему - обобщить всю информацию, относящуюся к ошибке: IndexError: list index out of range А также чтобы показать как определить почему и где в коде эта оши...

Суть этой ошибки очень проста — попытка обратиться к элементу списка/массива с несуществующим индексом.

Пример:

lst = [1, 2, 3]
print(lst[3])

вывод:

----> 2 print(lst[3])

IndexError: list index out of range

Указанный в примере список имеет три элемента. Индексация в Python начинается с 0 и заканчивается n-1, где n — число элементов списка (AKA длина списка).
Соответственно для списка lst валидными индексами являются: 0, 1 и 2.

В Python также имеется возможность индексации от конца списка. В этом случае используются отрицательные индексы: -1 — последний элемент, -2 — второй с конца элемент, …, -n-1 — второй с начала, -n — первый с начала.

Т.е. если указать отрицательный индекс, значение которого превышает длину списка мы получим всё ту же ошибку:

In [2]: lst[-4]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-2-ad46a138c96e> in <module>
----> 1 lst[-4]

IndexError: list index out of range

В реальной жизни (коде) эта ошибку чаще всего возникает в следующих ситуациях:

  • если список пустой: lst = []; first = lst[0]
  • в циклах — когда переменная итерирования (по индексам) дополнительно изменяется или когда используются глобальные переменные
  • в циклах при использовании вложенных списков — когда перепутаны индексы строк и столбцов
  • в циклах при использовании вложенных списков — когда размерности вложенных списков неодинаковые и код этого не учитывает. Пример: data = [[1,2,3], [4,5], [6,7,8]] — если попытаться обратиться к элементу с индексом 2 во втором списке ([4,5]) мы получим IndexError
  • в циклах — при изменении длины списка в момент итерирования по нему. Классический пример — попытка удаления элементов списка при итерировании по нему.

Поиск и устранения ошибки начинать нужно всегда с того, чтобы внимательно прочитать сообщение об ошибке (error traceback).

Пример скрипта (test.py), в котором переменная итерирования цикла for <variable>
изменяется (так делать нельзя):

lst = [1,2,3]
res = []

for i in range(len(lst)):
  i += 1   # <--- НЕ ИЗМЕНЯЙТЕ переменную итерирования!
  res.append(lst[i] ** 2)

Ошибка:

Traceback (most recent call last):
  File "test.py", line 6, in <module>
    res.append(lst[i] ** 2)
IndexError: list index out of range

Обратите внимание что в сообщении об ошибке указан номер ошибочной строки кода — File "test.py", line 6 и сама строка, вызвавшая ошибку: res.append(lst[i] ** 2). Опять же в реальном коде ошибка часто возникает в функциях, которые вызываются из других функций/модулей/классов. Python покажет в сообщении об ошибке весь стек вызовов — это здорово помогает при отладке кода в больших проектах.

После этого — мы точно знаем в каком месте кода возникает ошибка и можем добавить в код отладочную информацию, например напечатать значения индекса, который вызвал ошибку, понять почему используется неправильный индекс и исправить ошибку.

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:

languages = ['Python', 'JavaScript', 'Java']

print(languages[1])
# JavaScript

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.

Here’s an example:

languages = ['Python', 'JavaScript', 'Java']

print(languages[3])
# IndexError: list index out of range

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.

languages = ['Python', 'JavaScript', 'Java']

i = 0

while i <= len(languages):
    print(languages[i])
    i += 1

# IndexError: list index out of range

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 <= len(languages).

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 <= 3. 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.

Here’s how:

languages = ['Python', 'JavaScript', 'Java']

i = 0

while i < len(languages):
    print(languages[i])
    i += 1
    
    # Python
    # JavaScript
    # Java

The condition now looks like this: while i < 3.

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:

for num in range(5):
  print(num)
    # 0
    # 1
    # 2
    # 3
    # 4

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.

languages = ['Python', 'JavaScript', 'Java']


for language in range(4):
  print(languages[language])
    # Python
    # JavaScript
    # Java
    # Traceback (most recent call last):
    #   File "<string>", line 5, in <module>
    # IndexError: list index out of range

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.

That is:

languages = ['Python', 'JavaScript', 'Java']


for language in range(len(languages)):
  print(languages[language])
    # Python
    # JavaScript
    # Java

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.

Happy coding!



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

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()

color = ['red', 'blue', 'green', 'pink']
print(color[len(color)])

Output:

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:

  • red – 0
  • blue – 1
  • green – 2
  • pink – 3

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.

Example 2: Python list index out of range in loop

def check(x):
    for i in x:
        print (x[i])

lst = [1,2,3,4]
check(lst)

Output:

Python List Index Out Of Range In Loop
Output

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

lst=[1, 2, 3, 4, 4, 6]
for i in range(0,len(lst)):
    if lst[i]==4:
        lst.pop(i)

Output:

IndexError: list index out of range

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:

color = ['red', 'blue', 'green', 'pink']
print(color[len(color)-1])

Output:

Lists Are Indexed From Zero
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:

def check(x):
    for i in range(0, len(x)):
        print (x[i])

lst = [1,2,3,4]
check(lst)

Output:

Use Range() In Loop
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:

lst=[1, 2, 3, 4, 4, 6]
lst = [x for x in lst if x != 4]
print(lst)

Output:

[1, 2, 3, 6]

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:

lst=[1, 2, 3, 4, 4, 6]
for i in range(len(lst)):
    if lst[i] == 4:
        lst.remove(4) # error
        print(lst)

# correct way
for i in range(lst.count(4)):
    lst.remove(4)

print(lst)

Output:

[1, 2, 3, 6]

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:

lst=[1, 2, 3, 4, 4, 6]
index = 0
while index < len(lst):
    print(lst[index])
    index += 1

Output:

1
2
3
4
4
6

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.

6+. Properly using For Loop

Code:

lst=[1, 2, 3, 4, 4, 6]
for i in range(len(lst)):
    print(lst[i])

Output:

1
2
3
4
4
6

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.

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:

lst=[1, 2, 3, 4, 4, 6]
try:
    for i in range(0,len(lst)+1):
        print(lst[i])
except IndexError:
    print("Index error reached")

Output:

1
2
3
4
4
6
Index error reached

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:

lst = [1, 2]

# case 1
try:
    value = lst[3]
except IndexError:
    value = "Some default value"

print(value)

# case 2
value = lst[3] if len(lst) > 3 else 'Some default value'

print(value)

Output:

Some default value
Some default value

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:

Python List Length | How to Find the Length of List in Python
How to use Python find() | Python find() String Method
Python next() Function | Iterate Over in Python Using next

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.

Happy Pythoning!

In this article, we are going to see how to fix – List Index Out of Range in Python

Why we get- List Index Out of Range in Python

The “list index out of your range” problem is likely something you’ve encountered if you’ve ever worked with lists. Even though this problem occurs frequently, it could be difficult for a new programmer to diagnose.

How to rise list index out of range:

Example 1: 

Here our list is 3 and we are printing with size 4 so in this case, it will create a list index out of range

Python3

Output:

IndexError: list index out of range

Example 2:

Here we are printing the same pattern without of index.

Python3

names = ["blue","red","green"]

for name in range(len(names) + 1):

    print(names[name])

Output:

Traceback (most recent call last):
 File "/home/6536be743dacb18c2fcc724dd5aa21c6.py", line 5, in <module>
   print(names[name])
IndexError: list index out of range

How to solve list index out of range

  • Using range()
  • Using Closing thoughts
  • Using Index()

Method 1: Using range()

The range is used to give a specific range, the Python range() function returns the sequence of the given number between the given range.

Syntax of range()

range(start, stop, step).

  • start: An optional number that identifies the beginning of the series. 0 is the default value if it’s left blank.
  • stop: An integer designating the point at which the sequence should end.
  • step-: optional and needed if you want to increase the increment by more than 1. 1 is the default value.

The stop parameter for the range() function is the value returned by the len() function.

Example of fix list out of range error:

Python3

names = ["blue," "red," "green"]

for name in range(len(names)):

    print(names[name])

Output:

blue,red,green

Method 2: Using in operator

Python3

names = ["blue," "red," "green"]

for i in names:

    print(i)

Output:

blue,red,green

Method 3: Using Index()

Here we are going to create a list and then try to iterate the list using the constant values in for loops.

Python3

li = [1,2 ,3, 4, 5]

for i in range(6):

    print(li[i])

Output:

1
2
3
4
5
IndexError: list index out of range

Reason of the error –  The length of the list is 5 and if we are an iterating list on 6 then it will generate the error.

Solving this error without using len() or constant Value:

To solve this error we will take the index of the last value of the list and then add one then it will become the exact value of length.

Python3

li = [1,2 ,3, 4, 5]

for i in range(li.index(li[-1])+1):

    print(li[i])

Output:

1
2
3
4
5

In this tutorial, you’ll learn how all about the Python list index out of range error, including what it is, why it occurs, and how to resolve it.

The IndexError is one of the most common Python runtime errors that you’ll encounter in your programming journey. For the most part, these these errors are quite easy to resolve, once you understand why they occur.

Throughout this tutorial, you’ll learn why the error occurs and walk through some scenarios where you might encounter it. You’ll also learn how to resolve the error in these scenarios.

The Quick Answer:

Quick Answer - Prevent a Python IndexError List Index Out of Range

What is the Python IndexError?

Let’s take a little bit of time to explore what the Python IndexError is and what it looks like. When you encounter the error, you’ll see an error message displayed as below:

IndexError: list index out of range

We can break down the text a little bit. We can see here that the message tells us that the index is out of range. This means that we are trying to access an index item in a Python list that is out of range, meaning that an item doesn’t have an index position.

An item that doesn’t have an index position in a Python list, well, doesn’t exist.

In Python, like many other programming languages, a list index begins at position 0 and continues to n-1, where n is the length of the list (or the number of items in that list).

This causes a fairly common error to occur. Say we are working with a list with 4 items. If we wanted to access the fourth item, you may try to do this by using the index of 4. This, however, would throw the error. This is because the 4th item actually has the index of 3.

Let’s take a look at a sample list and try to access an item that doesn’t exist:

# How to raise an IndexError
a_list = ['welcome', 'to', 'datagy']
print(a_list[3])

# Returns:
# IndexError: list index out of range

We can see here that the index error occurs on the last item we try to access.

The simplest solution is to simply not try to access an item that doesn’t exist. But that’s easier said than done. How do we prevent the IndexError from occurring? In the next two sections, you’ll learn how to fix the error from occurring in their most common situations: Python for loops and Python while loops.

Need to check if a key exists in a Python dictionary? Check out this tutorial, which teaches you five different ways of seeing if a key exists in a Python dictionary, including how to return a default value.

Python IndexError with For Loop

You may encounter the Python IndexError while running a Python for loop. This is particularly common when you try to loop over the list using the range() function.

Let’s take a look at the situation where this error would occur:

# How to raise an IndexError with a For Loop
a_list = ['welcome', 'to', 'datagy']

for i in range(len(a_list) + 1):
    print(a_list[i])

# Returns:
# welcome
# to
# datagy
# Traceback (most recent call last):
# IndexError: list index out of range

The way that we can fix this error from occurring is to simply stop the iteration from occurring before the list runs out of items. The way that we can do this is to change our for loop from going to our length + 1, to the list’s length. When we do this, we stop iterating over the list’s indices before the lengths value.

This solves the IndexError since it causes the list to stop iterating at position length - 1, since our index begins at 0, rather than at 1.

Let’s see how we can change the code to run correctly:

# How to prevent an IndexError with a For Loop
a_list = ['welcome', 'to', 'datagy']

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

# Returns:
# welcome
# to
# datagy

Now that you have an understanding of how to resolve the Python IndexError in a for loop, let’s see how we can resolve the error in a Python while-loop.

Want to learn more about Python for-loops? Check out my in-depth tutorial that takes your from beginner to advanced for-loops user! Want to watch a video instead? Check out my YouTube tutorial here.

Python IndexError with While Loop

You may also encounter the Python IndexError when running a while loop.

For example, it may be tempting to run a while loop to iterate over each index position in a list. You may, for example, write a program that looks like this:

# How to raise an IndexError with a While Loop
a_list = ['welcome', 'to', 'datagy']

i = 0
while i <= len(a_list):
    print(a_list[i])
    i += 1

# Returns:
# welcome
# to
# datagy
# IndexError: list index out of range

The reason that this program fails is that we iterate over the list one too many times. The reason this is true is that we are using a <= (greater than or equal to sign). Because Python list indices begin at the value 0, their max index is actually equal to the number of items in the list minus 1.

We can resolve this by simply changing the operator a less than symbol, <. This prevents the loop from looping over the index from going out of range.

# How to prevent an IndexError with a While Loop
a_list = ['welcome', 'to', 'datagy']

i = 0
while i < len(a_list):
    print(a_list[i])
    i += 1

# Returns:
# welcome
# to
# datagy

In the next section, you’ll learn a better way to iterate over a Python list to prevent the IndexError.

Want to learn more about Python f-strings? Check out my in-depth tutorial, which includes a step-by-step video to master Python f-strings!

How to Fix the Python IndexError

There are two simple ways in which you can iterate over a Python list to prevent the Python IndexError.

The first is actually a very plain language way of looping over a list. We don’t actually need the list index to iterate over a list. We can simply access its items directly.

# Prevent an IndexError
a_list = ['welcome', 'to', 'datagy']

for word in a_list:
    print(word)

# Returns:
# welcome
# to
# datagy

This directly prevents Python from going beyond the maximum index.

Want to learn how to use the Python zip() function to iterate over two lists? This tutorial teaches you exactly what the zip() function does and shows you some creative ways to use the function.

But what if you need to access the list’s index?

If you need to access the list’s index and a list item, then a much safer alternative is to use the Python enumerate() function.

When you pass a list into the enumerate() function, an enumerate object is returned. This allows you to access both the index and the item for each item in a list. The function implicitly stops at the maximum index, but allows you to get quite a bit of information.

Let’s take a look at how we can use the enumerate() function to prevent the Python IndexError.

# Prevent an IndexError with enumerate()
a_list = ['welcome', 'to', 'datagy']

for idx, word in enumerate(a_list):
    print(idx, word)

# Returns:
# 0 welcome
# 1 to
# 2 datagy

We can see here that we the loop stops before the index goes out of range and thereby prevents the Python IndexError.

Check out some other Python tutorials on datagy, including our complete guide to styling Pandas and our comprehensive overview of Pivot Tables in Pandas!

Conclusion

In this tutorial, you learned how to understand the Python IndexError: list item out of range. You learned why the error occurs, including some common scenarios such as for loops and while loops. You learned some better ways of iterating over a Python list, such as by iterating over items implicitly as well as using the Python enumerate() function.

To learn more about the Python IndexError, check out the official documentation here.


In this python tutorial, we look at why we receive the IndexError: List index out of range error in python, post which we look at solutions for the error.

Table of Contents- list index out of range python

  • Why do we get the list index out of range python error?
  • Solution using range() and len()
  • Closing thoughts — list index out of range python

Why do we get the list index out of range Python error?

If you have worked with lists before, the chances of you coming across the ‘list index out of your range’ error is quite high. This error is quite common and for a new programmer debugging this error, it could be tricky

So let us first understand how indexes work and then look at the solutions for the list index out of range error.

Lists are used to store multiple values in a single variable. Once stored, each value is given a unique position, these positions are called indexes. These indexes are used to access a particular value in a list. Furthermore, Python lists are 0-indexed, which means the index of the first value is 0 and the last index is n-1.

Let me explain this with an example, consider a list x = ["Hire", "top", "freelancers"], the index of "Hire", "top" and "freelancers" is x[0], x[1] and x[2] respectively. And trying to return x[3] is when you receive a List index out of range error in Python.

Now that we have understood indexing, let’s look at more instances when we come across the list index out of range error.

Solution using range() and len():

While looping through a list, most new programmers make the mistake of hard coding the number of iterations. This is not a good practice as adding or removing an item from the list would break your loop.

To foolproof your loop of such instances, the range() function along with len() would return the length of the list dynamically. Subsequently preventing you from receiving the ‘list index out of range’ error in python.

The range() function returns a sequence of numbers starting from 0, and ends at the integer passed as a parameter. We use this method along with the len() function. This function returns the length of the parameter passed. This way no matter the length of the list, we would not go out of range.

We pass the return value of the len() function as the parameter for the range() function.

Syntax of range()

range(start, stop, step)

Parameters

start — Optional, an integer that indicates the start of the sequence. In case it’s left empty, 0 is the default value

stop — An integer that indicates where the sequence should stop

step — Optional, and used in case you would like to increment by a number greater than 1. The default value is 1

We pass the return value of the len() function as the stop parameter for the range() function.

Code to fix list out of range error:

list1 = ["Hire", "the", "top", 10, "python","freelancers"]

for i in range(0,len(list1)):
    print(list1[i])

Through this method, the loop runs from 0 right up to 5 i.e, the length of the list passed into the len() function. This was to avoid the ‘list index out of range’ error.

Closing thoughts — list index out of range python

Although the above method solves the ‘list index out of range’ error, another caveat while dealing with list indexes is as follows. Programmers often use the wrong variable to index a list. This example would give you a better understanding.

list1 = [5,10,15,20,25]

for i in list1:
    print(list1[i])

Note that this code is iterating over the values in the list. Here i iterates over the value in the list and in the first iteration, list1[i] refers to the 5th index. Subsequently, the 10th index is referenced in the second iteration, and since the list only consists of 5 values python returns the ‘index out of range’ error.

This is another case that you should be aware of to avoid the error

The python error IndexError: list index out of range occurs when an incorrect indices is used to access a list element. The index value should not be out of range. Otherwise IndexError will be thrown. For example, if you try to access indices that are outside the index range in the list, python interpreter will throw the error IndexError: list index out of range.

The common reason for the exception IndexError: list index out of range is that

  • The list is iterated with index starting from 1 instead of 0.
  • The last item is accessed with the length of the list. It is expected to be Len(list)-1.
  • The item in the list is deleted when iterating the list. If an element is deleted, the index value will be reduced by one.

Let’s look at an example where the error happens. If there are 3 elements in a python list the index will be from 0 to 2. The index always begins with the 0. The last index is the element total minus one. If there are 3 elements in the list the last index is 2. If an index value is out of this range, then it will throw the error.

The list, such as tuple, array, string, uses the index to identify the element in the list. Each index contains an element of a list. If an incorrect index is used to locate an element in a list, the list index out of range exception will be thrown. The IndexError: list index out of range error occurs in Python when you attempt to access an unknown element outside the list index. The list index is used to identify the items in the list. This error occurs when access is outside the index range of the list.

Exception

The error will be thrown as like below. The IndexError is seen when the error in the list index occurs.

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 2, in <module>
    print (a[5])
IndexError: list index out of range
[Finished in 0.0s with exit code 1]

How to reproduce this error

If an undefined element is tried to access using an index beyond the allowed limit, python interpreter will throw this error message. In the example below, the list contains five elements and index value is from 0 to 4. If you try to access the element in index 5. python will throw the error IndexError: list index out of range.

a = [2,4,6,8,10]
print (a[5])

Output

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 2, in <module>
    print (a[5])
IndexError: list index out of range
[Finished in 0.0s with exit code 1]

Root Cause

In python, if an undefined element is tried using an index beyond the allowed index value in objects such as list, tuple, and string, the python interpreter can not identify the element from the index. In this case, the python interpreter will throw an error called IndexError: list index out of range

Based on the type of object used, it throws various error messages such as IndexError: tuple index out of range and IndexError: string index out of range. 

Forward index of the list

Python supports two indexing types, forward indexing and backward indexing. The forward index will start at 0 and end with the number of elements in the list. The forward index is used to iterate a element in the forward direction. The element in the list is printed in the same index sequence. The index value is increased to the next index value.

index 0 1 2 3 4
value a b c d e

Backward index of the list

Python is supporting backward indexing. The back index starts from-1 and the index ends with the negative value of the number of elements in the list. The backward index is used to iterate the elements in the backward direction. The element in the list is printed in the reverse sequence of the index. The index value is decremented to get the next index value. The back index is as shown below

Index -5 -4 -3 -2 -1
Value a b c d e

Solution 1

The index value should be within the range of the allowed index value. Normally, the list contains index starting from 0 to the length of the list. The negative index value starting from -1 will point to the last index of the list.

The list in this example contains 5 elements. Index values start at 0 and the last index value is 4. Python allows the list to be accessed in reverse order. The reverse index will begin with -5 and will end with -1. If the index value is different from the value listed, the list index out of range exception will be thrown.

a = [2,4,6,8,10]
print (a[3])

Output

8
[Finished in 0.1s]

Solution 2 – Using len() function

The list is dynamically created in real time. The list is iterated and the elements are retrieved based on the index. In that case , the value of the index is unpredictable. If the element in the list is retrieved by an index, the index value should be validated with the length of the list.

a = [2,4,6,8,10]
index = 3
if index < len(a) :
	print a[index]

Output

8
[Finished in 0.1s]

Solution 3 – for loop with ‘in’

The python membership operator is used to iterate all the elements in the list. The membership operator uses to get all the elements in the list without using the element index. The loop helps to iterate all the elements in the list. The example below shows how to use a membership in a loop. The error IndexError: list index out of range will be resolved by the membership operators.

a = [2,4,6,8,10]
for item in a:
	print item

Output

2
4
6
8
10
[Finished in 0.0s]

Solution 4 – for loop with range()

The range function should be used to iterate the items in the list. the range will give the values starting from 0 and ends with value less one. The list index starts with 0. The range function will help in iterating items in the for loop.

a = [2,4,6,8,10]
for i in range(len(a)):
	print a[i]

Output

2
4
6
8
10
[Finished in 0.1s]

Solution 5 – for loop with reversed()

If a list is iterated to delete an item in the list, the list index out of range exception will be thrown. If an item is deleted in the list, the index values will be reduced by one. The last index does not contain item. If a list is iterated in reversed order to delete an item, the index will not be changed for the iterating index values. The example below will show how to delete a item from a list.

a = [2,4,6,8,10]
for i in reversed(range(len(a))):
	if i==3 :
		a.pop(i)
		
for i in reversed(range(len(a))):
	print(a[i])

Output

10
6
4
2
[Finished in 0.1s]

Ситуация: у нас есть проект, в котором мы математически моделируем игру в рулетку. Мы хотим обработать отдельно нечётные числа, которые есть на рулетке, — для этого нам нужно выбросить из списка все чётные. Проверка простая: если число делится на 2 без остатка — оно чётное и его можно удалить. Для этого пишем такой код:

# в рулетке — 36 чисел, не считая зеро
numbers = [n for n in range(36)]
# перебираем все числа по очереди
for i in range(len(numbers)):
    # если текущее число делится на 2 без остатка
    if numbers[i] % 2 == 0:
        # то убираем его из списка
        del numbers[i]

Но при запуске компьютер выдаёт ошибку:

❌ IndexError: list index out of range

Почему так произошло, ведь мы всё сделали правильно?

Что это значит: компьютер на старте цикла получает и запоминает одну длину списка с числами, а во время выполнения эта длина меняется. Компьютер, держа в памяти старую длину, пытается обратиться по номерам к тем элементам, которых уже нет в списке. 

Когда встречается: когда программа одновременно использует список как основу для цикла и тут же в цикле добавляет или удаляет элементы списка.

В нашем примере случилось вот что:

  1. Мы объявили список из чисел от 1 до 36.
  2. Организовали цикл, который зависит от длины списка и на первом шаге получает его размер.
  3. Внутри цикла проверяем на чётность, и если чётное — удаляем число из списка.
  4. Фактический размер списка меняется, а цикл держит в голове старый размер, который больше.
  5. Когда мы по старой длине списка обращаемся к очередному элементу, то выясняется, что список закончился и обращаться уже не к чему.
  6. Компьютер останавливается и выводит ошибку.

Что делать с ошибкой IndexError: list index out of range

Основное правило такое: не нужно в цикле изменять элементы списка, если список используется для организации этого же цикла. 

Если нужно обработать список, то результаты можно складывать в новую переменную, например так:

# в рулетке — 36 чисел, не считая зеро
numbers = [n for n in range(36)]
# новый список для нечётных чисел
new_numbers = []
# перебираем все числа по очереди
for i in range(len(numbers)):
    # если текущее число не делится на 2 без остатка
    if numbers[i] % 2 != 0:
        # то добавляем его в новый список
        new_numbers.append(numbers[i])

Вёрстка:

Кирилл Климентьев

Python List Index Out of Range

If you are working with lists in Python, you have to know the index of the list elements. This will help you access them and perform operations on them such as printing them or looping through the elements. But in case you mention an index in your code that is outside the range of the list, you will encounter an IndexError.

List index out of range” error occurs in Python when we try to access an undefined element from the list.

The only way to avoid this error is to mention the indexes of list elements properly.

Example: 

# Declaring list
list_fruits = ['apple', 'banana', 'orange']
# Print value of list at index 3
print(list_fruits[3]);

Output:

Traceback (most recent call last):
  File "list-index.py", line 2, in <module>
    print(list_fruits[3]);
IndexError: list index out of range


In the above example, we have created a list named “list_fruits” with three values apple, banana, and orange. Here we are trying to print the value at the index [3].

And we know that the index of a list starts from 0 that’s why in the list, the last index is 2, not 3

Due to which if we try to print the value at index [3] it will give an error.

Indexerror: list Index Out of Range in Python

Correct Example: 

# Declaring list
list_fruits = ['Apple', 'Banana', 'Orange']
# Print list element at index 2
print(list_fruits[2]);

Output: 

Orange

1. Example with «while» Loop

# Declaring list
list_fruits = ['Apple', 'Banana', 'Orange']

i=0
# while loop less then and equal to list "list_fruits" length.
while i <= len(list_fruits):
    print(list_fruits[i])
    i += 1


Output:

Apple
Banana
Orange
Traceback (most recent call last):
  File "list-index-while.py", line 5, in <module>
    print(list_fruits[i])
IndexError: list index out of range

In the above case, the error occurs inline 5, as shown in output where print(list_fruits[i]) means that the value of “i” exceeds the index value of list “list_fruits.”

If you need to check why this error occurs, print the value of “i” just before “print(list_fruits[i])” statement.

print(list_fruits[i])

Example

# declaring list
list_fruits = ['Apple', 'Banana', 'Orange']

i=0
# while loop less then and equal to list "list_fruits" length.
while i <= len(list_fruits):
    # print the value of i
    print(i)
    # print value of list
    print(list_fruits[i])
    i += 1

Output:

0
Apple
1
Banana
2
Orange
3
Traceback (most recent call last):
  File "list-index-while.py", line 9, in <module>
    print(list_fruits[i])
IndexError: list index out of rang

In the above example output, we can see that the value of ‘i’ goes to “3”, whereas our list index is only up to 2.

Solution for this error 

# declaring list
list_fruits = ['Apple', 'Banana', 'Orange']

i=0
# while loop less then list "list_fruits" length
while i < len(list_fruits):
    # print the value of i
    print(i)
    # print value of list
    print(list_fruits[i])
    i += 1

Output:

0
Apple
1
Banana
2
Orange

2. Example with «for» Loop:

# declaring list

list_fruits = ['Apple', 'Banana', 'Orange']

# for loop to print the index from 0 to 3

for i in range(0,4):
    # print the value of i
    print(i)
    # print value of list
print(list_fruits[i])


Output:

0
Apple
1
Banana
2
Orange
3
Traceback (most recent call last):
  File "list-index-for.py", line 9, in <module>
    print(list_fruits[i])
IndexError: list index out of range

In the above example, we are printing the value at index 3, but the out list has indexed only up to 2.

To avoid such type of error, we have to run for loop in the range of “list” length.

Solution:

# declaring list
list_fruits = ['Apple', 'Banana', 'Orange']

# for loop to print the index in the range of list length
for i in range(len(list_fruits)):
    # print the value of i
    print(i)
    # print value of list
print(list_fruits[i])

Output:

0
Apple
1
Banana
2
Orange

Conclusion

We have seen the different situations where the list index out of range error might occur. You can check the length of the list using before performing operations or using the indexes.

IndexErrors are one of the most common types of runtime errors in Python. They’re raised when you try to access an index value inside a Python list that does not exist. In most cases, index errors are easy to resolve. You just need to do a little bit of debugging.

In this tutorial, we’re going to talk about the “indexerror: list index out of range” error. We’ll discuss how it works and walk through an example scenario where this error is present so that we can solve it.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

The Problem: indexerror: list index out of range

As always, the best place to start is to read and break down our error message: 

indexerror: list index out of range

This error message tells us that we’re trying to access a value inside an array that does not have an index position.

In Python, index numbers start from 0. Here’s a typical Python array:

programming_languages = ["Java", "Python", "C++"]

This array contains three values. The first list element, Java, has the index value 0. Each subsequent value has an index number 1 greater than the last. For instance, Python’s index value is 1.

If we try to access an item at the index position 3, an error will be returned. The last item in our array has the index value 2.

Example Scenarios (and Solutions)

There are two common scenarios in which the “list index out of range” error is raised:

  • When you try to iterate through a list and forget that lists are indexed from zero.
  • When you forget to use range() to iterate over a list.

Let’s walk through both of these scenarios.

Lists Are Indexed From Zero

The following program prints out all the values in a list called “programming_languages” to the Python shell:

programming_languages = ["Java", "Python", "C++"]
count = 0 

while count <= len(programming_languages):
	print(programming_languages[count])
	count += 1

First, we have declared two variables. The variable “programming_languages” stores the list of languages that we want to print to the console. The variable “count” is used to track how many values we have printed out to the console.

Next, we have declared a while loop. This loop prints out the value from the “programming_languages” at the index position stored in “count”. Then, it adds 1 to the “count” variable. This loop continues until the value of “count” is no longer less than or equal to the length of the “programming_languages” list.

Let’s try to run our code:

Java
Python
C++
Traceback (most recent call last):
  File "main.py", line 5, in <module>
	print(programming_languages[count])
IndexError: list index out of range

All the values in our list are printed to the console but an error is raised. The problem is that our loop keeps going until the value of “count” is no longer less than or equal to the length of “programming_languages”. This means that its last iteration will check for:

This value does not exist. This causes an IndexError. To solve this problem, we can change our operator from <= to <. This will ensure that our list only iterates until the value of “count” is no longer less than the length of “programming_languages”. Let’s make this revision:

programming_languages = ["Java", "Python", "C++"]
count = 0 

while count < len(programming_languages):
	print(programming_languages[count])
	count += 1

Our code returns:

We’ve successfully solved the error! Our loop is no longer trying to print out programming_languages[3]. It stops when the value of “count” is equal to 3 because 3 is not less than the length of “programming_languages”.

Forget to Use range()

When you’re iterating over a list of numbers, it’s easy to forget to include a range() statement. If you are accessing items in this list, an error may be raised.

Consider the following code:

ages = [9, 10, 9]

for age in ages:
	print(ages[age])

This code should print out all the values inside the “ages” array. This array contains the ages of students in a middle school class. Let’s run our program and see what happens:

Traceback (most recent call last):
  File "main.py", line 4, in <module>
	print(ages[age])
IndexError: list index out of range

An error is raised. Let’s add a print statement inside our loop to see the value of “age” in each iteration to see what has happened:

ages = [9, 10, 9]

for age in ages:
	print(age)
	print(ages[age])

Our code returns:

9
Traceback (most recent call last):
  File "main.py", line 5, in <module>
	print(ages[age])
IndexError: list index out of range

The first age, 9, is printed to the console. However, the value of “age” is an actual value from “ages”. It’s not an index number. On the “print(ages[age])” line of code, we’re trying to access an age by its index number.

When we run our code, it checks for: ages[9]. The value of “age” is 9 in the first iteration. There is no item in our “ages” list with this value.

To solve this problem, we can use a range() statement to iterate through our list of ages:

ages = [9, 10, 9]

for age in range(0, len(ages)):
	print(ages[age])

Let’s run our code again:

All of the values from the “ages” array are printed to the console. The range() statement creates a list of numbers in a particular range. In this case, the range [0, 1, 2] is created. These numbers can then be used to access values in “ages” by their index number.

Venus profile photo

«Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!»

Venus, Software Engineer at Rockbot

Alternatively, we could use a “for…in” loop without using indexing:

ages = [9, 10, 9]

for age in ages:
	print(age)

This code returns:

Our code does not try to access any values by index from the “ages” array. Instead, our loop iterates through each value in the “ages” array and prints it to the console.

Conclusion

IndexErrors happen all the time. To solve the “indexerror: list index out of range” error, you should make sure that you’re not trying to access a non-existent item in a list.

If you are using a loop to access an item, make sure that loop accounts for the fact that lists are indexed from zero. If that does not solve the problem, check to make sure that you are using range() to access each item by its index value.

Now you’re ready to solve the “indexerror: list index out of range” error like a Python expert!

Понравилась статья? Поделить с друзьями:
  • Index was outside the bounds of the array ошибка
  • Index php 500 internal server error
  • Index is out of date как исправить
  • Index exceeds matrix dimensions матлаб как исправить
  • Index error tuple index out of range