Indexerror list index out of range python как исправить

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

Пример:

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 Occur in Python when an item from a list is tried to be accessed that is outside the range of the list. Before we proceed to fix the error, let’s discuss how indexing work in Python.

What Causes IndexError

When you attempt to access an index of a sequence (such as a list or a string) that is out of range, an IndexError is raised. Sequences in Python are zero-indexed, which means that the first element’s index is 0, the second element’s index is 1, and so on. An IndexError will be returned if you attempt to access an index that is longer than or equal to the length of the sequence.

Examples

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

    print(j[4])
          ~^^^
IndexError: list index out of range

Similarly, we can also get an IndexError when using negative indices. For example:

Python3

my_string = "Geeksforgeeks"

print(my_string[-61])

Output

    print(my_string[-61])
          ~~~~~~~~~^^^^^
IndexError: string index out of range

How to Fix IndexError in Python

Let’s see some examples that showed how we may solve the error.

  • Using Python range()
  • Using Python “in” keyword
  • Using Python Index()
  • Using Try Except Block

Using range()

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

Python3

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

for name in range(len(names)):

    print(names[name])

Output

blue,red,green

Using Python “in” keyword

The in keyword is used to check if a value is present in a sequence. The in keyword is also used to iterate through a sequence in a Python for loop.

Python3

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

for i in names:

    print(i)

Output

blue,red,green

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 for 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

Using Try Except Block

If we expect that an index might be out of range, we can use a try-except block to handle the error gracefully.

Python3

my_list = [1, 2, 3]

try:

    print(my_list[3])

except IndexError:

    print("Index is out of range")

Output

Index is out of range

Last Updated :
05 May, 2023

Like Article

Save Article

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

The IndexError: list index out of range error occurs in Python when an item from a list is attempted to be accessed that is outside the index range of the list.

Install the Python SDK to identify and fix exceptions

What Causes IndexError

This error occurs when an attempt is made to access an item in a list at an index which is out of bounds. The range of a list in Python is [0, n-1], where n is the number of elements in the list. When an attempt is made to access an item at an index outside this range, an IndexError: list index out of range error is thrown.

Python IndexError Example

Here’s an example of a Python IndexError: list index out of range thrown when trying to access an out of range list item:

test_list = [1, 2, 3, 4]
print(test_list[4])

In the above example, since the list test_list contains 4 elements, its last index is 3. Trying to access an element an index 4 throws an IndexError: list index out of range:

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

How to Fix IndexError in Python

The Python IndexError: list index out of range can be fixed by making sure any elements accessed in a list are within the index range of the list. This can be done by using the range() function along with the len() function.

The range() function returns a sequence of numbers starting from 0 ending at the integer passed as a parameter. The len() function returns the length of the parameter passed. Using these two methods together for a list can help iterate over it until the item at its last index and helps avoid the error.

The above approach can be used in the earlier example to fix the error:

test_list = [1, 2, 3, 4]

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

The above code runs successfully and produces the correct output as expected:

1
2
3
4

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Sign Up Today!

Ситуация: у нас есть проект, в котором мы математически моделируем игру в рулетку. Мы хотим обработать отдельно нечётные числа, которые есть на рулетке, — для этого нам нужно выбросить из списка все чётные. Проверка простая: если число делится на 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])

Вёрстка:

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

Понравилась статья? Поделить с друзьями:
  • Как найти координаты потерянного телефона
  • Как найти массу соли в массе кристаллогидрата
  • Как найти наибольшую относительную погрешность
  • Как через телеграмм найти местоположение человека
  • Как найти сумму элементов ниже главной диагонали