Почему я получаю ошибку "IndexError: list index out of range" и как ее исправить?
Цель создания данного вопроса и ответа к нему — обобщить всю информацию, относящуюся к ошибке:
А также чтобы показать как определить почему и где в коде эта ошибка возникает и привести более-менее канонический ответ, чтобы ссылаться на него в будущем.
PS ответ планируется дополнять новыми примерами.
Суть этой ошибки очень проста — попытка обратиться к элементу списка/массива с несуществующим индексом.
Указанный в примере список имеет три элемента. Индексация в Python начинается с 0 и заканчивается n-1 , где n — число элементов списка (AKA длина списка). Соответственно для списка lst валидными индексами являются: 0 , 1 и 2 .
В Python также имеется возможность индексации от конца списка. В этом случае используются отрицательные индексы: -1 — последний элемент, -2 — второй с конца элемент, . -n-1 — второй с начала, -n — первый с начала.
Т.е. если указать отрицательный индекс, значение которого превышает длину списка мы получим всё ту же ошибку:
В реальной жизни (коде) эта ошибку чаще всего возникает в следующих ситуациях:
- если список пустой: lst = []; first = lst[0]
- в циклах — когда переменная итерирования (по индексам) дополнительно изменяется или когда используются глобальные переменные
- в циклах при использовании вложенных списков — когда перепутаны индексы строк и столбцов
- в циклах при использовании вложенных списков — когда размерности вложенных списков неодинаковые и код этого не учитывает. Пример: data = [[1,2,3], [4,5], [6,7,8]] — если попытаться обратиться к элементу с индексом 2 во втором списке ( [4,5] ) мы получим IndexError
- в циклах — при изменении длины списка в момент итерирования по нему. Классический пример — попытка удаления элементов списка при итерировании по нему.
Поиск и устранения ошибки начинать нужно всегда с того, чтобы внимательно прочитать сообщение об ошибке ( error traceback ).
Пример скрипта ( test.py ), в котором переменная итерирования цикла for <variable> изменяется (так делать нельзя):
Обратите внимание что в сообщении об ошибке указан номер ошибочной строки кода — File "test.py", line 6 и сама строка, вызвавшая ошибку: res.append(lst[i] ** 2) . Опять же в реальном коде ошибка часто возникает в функциях, которые вызываются из других функций/модулей/классов. Python покажет в сообщении об ошибке весь стек вызовов — это здорово помогает при отладке кода в больших проектах.
После этого — мы точно знаем в каком месте кода возникает ошибка и можем добавить в код отладочную информацию, например напечатать значения индекса, который вызвал ошибку, понять почему используется неправильный индекс и исправить ошибку.
Индекс списка вне диапазона в Python: Ошибка и решение
Индекс списка Python вне диапазона возникает, когда мы пытаемся получить доступ к недопустимому индексу в нашем списке. Чтобы избежать этого, обязательно оставайтесь в пределах досягаемости.
- Автор записи
Привет, кодеры! В этой статье мы узнаем об ошибке python list index out of range, а также о том, как её устранить. Сначала мы должны понять, что это значит? Ошибка Индекс списка вне диапазона возникает, когда мы пытаемся получить доступ к недопустимому индексу в нашем списке Python.
Иллюстрация list index out of range с примерами:
Пример 1: с функцией len()
выход:
Объяснение:
В этом фрагменте кода мы создали список под названием color, содержащий четыре элемента – красный, синий, зеленый, розовый.
В python индексация элементов списка начинается с 0. Таким образом, соответствующие индексы элементов следующие:
- красный – 0
- синий – 1
- зеленый – 2
- розовый – 3
Длина списка равна 4. Таким образом, когда мы пытаемся получить доступ к color[len(color)] , мы получаем доступ к элементу color[4] , который не существует и выходит за пределы диапазона списка. В результате отображается ошибка list index out of range.
пример 2: с использованием цикла
выход:
Объяснение:
Здесь список lst содержит значение 1,2,3,4 , имеющее индекс 0,1,2,3 соответственно.
Когда цикл повторяется, значение i равно элементу, а не его индексу.
Таким образом, когда значение i равно 1 (то есть первый элемент), он отображает значение x[1], которое равно 2, и так далее.
Но когда значение i становится 4, он пытается получить доступ к индексу 4, то есть x[4], который становится вне границы, таким образом отображая сообщение об ошибке.
Как избежать ошибки выхода индекса списка python из диапазона?
1)Списки индексируются с нуля:
Мы должны помнить, что индексация в списке python начинается с 0, а не с 1. Итак, если мы хотим получить доступ к последнему элементу списка, оператор должен быть записан как lst[len-1] , а не last[long], где len – количество элементов, присутствующих в списке.
Итак, первый пример можно исправить следующим образом:
выход:
объяснение:
Теперь, когда мы использовали color[lens(color)-1], он обращается к элементу color[3], который является последним элементом списка. Таким образом, вывод отображается без каких-либо href=”https://en.m.wikipedia.org/wiki/Error”>ошибка. href=”https://en.m.wikipedia.org/wiki/Error”>ошибка.
2)Используйте range() в цикле:
Когда вы перебираете список чисел, то range() должен использоваться для доступа к индексу элементов. Мы забываем использовать его вместо индекса, доступ к самому элементу осуществляется, что может привести к ошибке индекса списка вне диапазона.
Итак, чтобы устранить ошибку второго примера, мы должны выполнить следующий код:
выход:
Объяснение:
Теперь, когда мы использовали функцию range() от 0 до длины списка, вместо прямого доступа к элементам списка мы получаем доступ к индексу списка, таким образом избегая каких-либо ошибок.
Обязательно Прочтите:
Python List Length | How to Find the Length of List in PythonHow to use Python and() | Python find() String MethodPython next() Function | Iterate Over in Python Using next
Вывод: Индекс списка Python Выходит за пределы диапазона
В повседневном программировании ошибка индекса списка вне диапазона очень распространена. Мы должны убедиться, что мы остаемся в пределах диапазона нашего списка, чтобы избежать этой проблемы. Чтобы избежать этого, мы должны проверить длину списка и код соответственно.
Однако, если у вас есть какие-либо сомнения или вопросы, дайте мне знать в разделе комментариев ниже. Я постараюсь помочь вам как можно скорее.
List index out of range python ошибка как исправить
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
List Index Out of Range – Python Error [Solved]

Ihechikara Vincent Abba
![List Index Out of Range – Python Error [Solved]](https://www.freecodecamp.org/news/content/images/size/w2000/2022/08/kelly-sikkema--1_RZL8BGBM-unsplash--3-.jpg)
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.
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 <= 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.
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:
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.