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

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

Вёрстка:

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

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

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.

Понравилась статья? Поделить с друзьями:
  • Indexerror list assignment index out of range ошибка
  • Index was outside the bounds of the array ошибка
  • Index python как избежать ошибки
  • Index php on line ошибка
  • Index out of bounds java ошибка