Ошибка array index is out of range

Очень часто при работе с массивами или коллекциями можно столкнуться с исключением: Index was out of range. В чём заключается суть ошибки.

Представьте, что у Вас есть массив, состоящий из двух элементов, например:

int [] ar = new int [] {5,7};

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

Обращение к элементам массива:

int a = ar[0];
int b = ar[1];

Результат: a = 5 и b = 7.

Но, стоит только указать неверный индекс, например:

int a = ar[2];

В результате получаем исключение: Index was outside the bounds of the array, то есть индекс находиться за границами диапазона, который в данном примере составляет от 0 до 1. Поэтому при возникновении данной ошибки, первое, что нужно сделать, так это убедиться в том, что Вы указали правильный индекс при обращении к элементу массива или обобщённой коллекции.

Exception

Так же данная ошибка очень часто встречается в циклах, особенно в цикле for, если Вы указываете неверное количество элементов содержащихся в массиве, например:

List<int> ar = new List<int> {8,9};
for (int i = 0; i < 3; i++)
{
int a = ar[i];
};

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

для массива

for (int i = 0; i < ar.Length; i++)
{
int a = ar[i];
};

для коллекции

List<int&gt; ar = new List<int> {5,7};
for (int i = 0; i < ar.Count; i++)
{
int a = ar[i];
}

Говоря про циклы нельзя не упомянуть ещё одну ошибку, которая очень часто встречается у многих начинающих программистов. Представим, что у нас есть две коллекции и нам нужно заполнить список var2 значениями из первого списка.

List<string> var = new List<string> {"c#", "visual basic", "c++"};
List<string> var2 = new List<string> {};
for (int i = 0; i < var.Count; i++)
{
var2[i] = var[i].ToString();
}

Не смотря на то, что вроде бы все указано, верно, в результате выполнения кода, уже на самом первом шаге цикла, будет выдано исключение: Index was out of range. Это связано с тем, что для заполнения коллекции var2 требуется использовать не индекс, а метод Add.

for (int i = 0; i < var.Count; i++)
{
var2.Add(var[i].ToString());
}

Если же Вы хотите отловить данное исключение, в ходе выполнения программы, то для этого достаточно воспользоваться блоками try catch, например:

try
{
for (int i = 0; i < var.Count; i++)
{
var2[i] = var[i].ToString();
}
}
catch (ArgumentOutOfRangeException e)
{
Console.WriteLine(e.Message);
}
}

Читайте также:

  • Как очистить listbox?
  • Динамическое добавление узлов в элементе TreeView
  • Поиск html элемента с атрибутом id


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

Пример:

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

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    C# supports the creation and manipulation of arrays, as a data structure. The index of an array is an integer value that has value in the interval [0, n-1], where n is the size of the array. If a request for a negative or an index greater than or equal to the size of the array is made, then the C# throws an System.IndexOutOfRange Exception. This is unlike C/C++ where no index of the bound check is done. The IndexOutOfRangeException is a Runtime Exception thrown only at runtime. The C# Compiler does not check for this error during the compilation of a program.

    Example:

    using System;

    public class GFG {

        public static void Main(String[] args)

        {

            int[] ar = {1, 2, 3, 4, 5};

            for (int i = 0; i <= ar.Length; i++)

                Console.WriteLine(ar[i]);

        }

    }

    Runtime Error:

    Unhandled Exception:
    System.IndexOutOfRangeException: Index was outside the bounds of the array.
    at GFG.Main (System.String[] args) <0x40bdbd50 + 0x00067> in :0
    [ERROR] FATAL UNHANDLED EXCEPTION: System.IndexOutOfRangeException: Index was outside the bounds of the array.
    at GFG.Main (System.String[] args) <0x40bdbd50 + 0x00067> in :0

    Output:

    1
    2
    3
    4
    5
    

    Here if you carefully see, the array is of size 5. Therefore while accessing its element using for loop, the maximum value of index can be 4 but in our program, it is going till 5 and thus the exception.

    Let’s see another example using ArrayList:

    using System;

    using System.Collections;

    public class GFG {

        public static void Main(String[] args)

        {

            ArrayList lis = new ArrayList();

            lis.Add("Geeks");

            lis.Add("GFG");

            Console.WriteLine(lis[2]);

        }

    }

    Runtime Error: Here error is a bit more informative than the previous one as follows:

    Unhandled Exception:
    System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
    Parameter name: index
    at System.Collections.ArrayList.get_Item (Int32 index) <0x7f2d36b2ff40 + 0x00082> in :0
    at GFG.Main (System.String[] args) <0x41b9fd50 + 0x0008b> in :0
    [ERROR] FATAL UNHANDLED EXCEPTION: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
    Parameter name: index
    at System.Collections.ArrayList.get_Item (Int32 index) <0x7f2d36b2ff40 + 0x00082> in :0
    at GFG.Main (System.String[] args) <0x41b9fd50 + 0x0008b> in :0

    Lets understand it in a bit of detail:

    • Index here defines the index we are trying to access.
    • The size gives us information of the size of the list.
    • Since size is 2, the last index we can access is (2-1)=1, and thus the exception

    The correct way to access array is :

    for (int i = 0; i < ar.Length; i++) 
    {
    }
    

    Handling the Exception:

    • Use for-each loop: This automatically handles indices while accessing the elements of an array.
      • Syntax:
        for(int variable_name in array_variable)
        {
             // loop body
        }
        
        
    • Use Try-Catch: Consider enclosing your code inside a try-catch statement and manipulate the exception accordingly. As mentioned, C# won’t let you access an invalid index and will definitely throw an IndexOutOfRangeException. However, we should be careful inside the block of the catch statement, because if we don’t handle the exception appropriately, we may conceal it and thus, create a bug in your application.

    Last Updated :
    23 Jan, 2019

    Like Article

    Save Article

    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!

    Понравилась статья? Поделить с друзьями:
  • Ошибка ark survival evolved fatal error
  • Ошибка an unreal process has crashed ue4
  • Ошибка an unknown exception has occurred герои 3 hd
  • Ошибка an unknown error occurred while accessing
  • Ошибка an unknown error occurred please try again