Меню

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 покажет в сообщении об ошибке весь стек вызовов — это здорово помогает при отладке кода в больших проектах.

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

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

Вёрстка:

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

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]

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Lisp ошибка лишняя закрывающая скобка на входе
  • Lion alcolmeter sd 400 ошибка e bl