Indexerror list index out of range 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])

In Python, the IndexError is a common exception that occurs when trying to access an element in a list, tuple, or any other sequence using an index that is outside the valid range of indices for that sequence. 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 an IndexError in Python

  • Accessing Non-Existent Index: 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.
  • Empty List: If you try to access an element from an empty list, an Indexerror will be raised since there are no elements in the list to access.

Example: 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.

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

  1. Check List Length: It’s important to check if an index is within the valid range of a list before accessing an element. To do so, you can use the function to determine the length of the list and make sure the index falls within the range of 0 to length-1.
  2. Use Conditional Statements: To handle potential errors, conditional statements like “if” or “else” blocks can be used. For example, an “if” statement can be used to verify if the index is valid before accessing the element.if or try-except blocks to handle the potential IndexError. For instance, you can use a if statement to check if the index is valid before accessing the element.

How to Fix List Index Out of Range in Python

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

  • Using Python range()
  • Using Python Index()
  • Using Try Except Block

Python Fix List Index Out of Range 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

Python Fix List Index Out of Range 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 Python 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

Python Fix List Index Out of Range 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 :
07 Aug, 2023

Like Article

Save Article

Hello coders!! In this article, we will learn about python list index out of range error and will also learn how to resolve such errors. At first, we should understand what does this means?

Python list index out of range arises when we try to access an invalid index in our Python list. In Python, lists can be initialized without mentioning the length of the list. This feature allows the users to add as much data to the list without encountering errors. But when accessing the data, you have to keep track of its index.

If you try to access the list index out of its range, it’ll throw an IndexError. Now, let us look into this topic deeply to have a better understanding.

What is IndexError Python List Index Out Of Range?

IndexError occurs when there is an invalid index passed to access the elements of the object. In python, the index starts from 0 and ranges till the length-1 of the list. Whenever the element is accessed from the list by using the square brackets, the __getitem__ method is called. This method first checks if the index is valid. The index cannot be float, or greater than or equal to the length of the list.

So, whenever you try to access the element which is not acceptable, IndexError is thrown. In our case, the index is out of the range, which means it’s greater than or equal to the length of the list. This error also applies to the indexing greater than the length of the string.

Causes of IndexError Python List Index Out Of Range?

There are several causes for this error to appear. Most of the causes are raised because the programmers assume that the list index starts from 1.

In Python, the list index begins from 0. Unfortunately, programmers who come from Lua, Julia, Fortran, or Matlab, are used to index the items from 1. In such cases, this error occurs.

There are many other scenarios where this error is raised, following are the examples of it –

Example 1: Python list index out of range with len()

color = ['red', 'blue', 'green', 'pink']
print(color[len(color)])

Output:

Python List Index Out Of Range With Len()
Output

Explanation:

In this code snippet, we have created a list called color having four elements – red, blue, green, pink

In python, the indexing of the elements in a list starts from 0. So, the corresponding index of the elements are:

  • red – 0
  • blue – 1
  • green – 2
  • pink – 3

The length of the list is 4. So, when we try to access color[len(color)], we are accessing the element color[4], which does not exist and goes beyond the range of the list. As a result, the list index out of bounds error is displayed.

Example 2: Python list index out of range in loop

def check(x):
    for i in x:
        print (x[i])

lst = [1,2,3,4]
check(lst)

Output:

Python List Index Out Of Range In Loop
Output

Explanation:

Here, the list lst contains the value 1,2,3,4 having index 0,1,2,3 respectively.

When the loop iterates, the value of i is equal to the element and not its index.

So, when the value of i is 1( i.e. the first element), it displays the value x[1] which is 2 and so on.

But when the value of i becomes 4, it tries to access the index 4, i.e. x[4], which becomes out of bound, thus displaying the error message.

Example 3: Case where your list length changes

lst=[1, 2, 3, 4, 4, 6]
for i in range(0,len(lst)):
    if lst[i]==4:
        lst.pop(i)

Output:

IndexError: list index out of range

Explanation:

In the above example, the user wants to remove the element if it matches a certain value. But the problem, in this case, is that while iterating, the length of your list is changing. So, when you reach the 6th iteration, the lst[6]==4 will throw an error because there is no 6th element in the list. When the two elements (4s) are removed the length of the list is reduced.

Solution for IndexError python list index out of range Error

The best way to avoid this problem is to use the len(list)-1 format to limit the indexation limits. This way you can not only avoid the indexing problems but also make your program more dynamic.

1. Lists are indexed from zero:

We need to remember that indexing in a python list starts from 0 and not 1. So, if we want to access the last element of a list, the statement should be written as lst[len-1] and not lst[len], where len is the number of elements present in the list.

So, the first example can be corrected as follows:

color = ['red', 'blue', 'green', 'pink']
print(color[len(color)-1])

Output:

Lists Are Indexed From Zero
Output

Explanation:

Now that we have used color[len(color)-1], it accesses the element color[3], which is the last element of the list. So, the output is displayed without any error.

2. Use range() in loop:

When one is iterating through a list of numbers, then range() must be used to access the elements’ index. We one forgets to use it, instead of index, the element itself is accessed, which may give a list index out of range error.

So, in order to resolve the error of the second example, we have to do the following code:

def check(x):
    for i in range(0, len(x)):
        print (x[i])

lst = [1,2,3,4]
check(lst)

Output:

Use Range() In Loop
Output

Explanation:

Now, that we have used the range() function from 0 to the length of the list, instead of directly accessing the elements of the list, we access the index of the list, thus avoiding any sort of error.

3. Avoiding pop() while iterating through the list

Code:

lst=[1, 2, 3, 4, 4, 6]
lst = [x for x in lst if x != 4]
print(lst)

Output:

[1, 2, 3, 6]

Explanation:

You can use the pop() function in a loop to remove the items from the list, but if you use the same list to change and iterate it’ll through an error. As an alternative to this, you can use the list comprehension along with an inline if to avoid adding elements to the list.

4. Avoiding remove() while iterating through the list

Code:

lst=[1, 2, 3, 4, 4, 6]
for i in range(len(lst)):
    if lst[i] == 4:
        lst.remove(4) # error
        print(lst)

# correct way
for i in range(lst.count(4)):
    lst.remove(4)

print(lst)

Output:

[1, 2, 3, 6]

Explanation:

In the above code, the user intends to remove all the occurrences of 4 from the list. But while iterating through the loop, the remove() function reduces its length. This causes an indexation error in lst[i]. As an alternative, you can use the range() function to use the remove() function a limited number of times. The count() function is amazingly helpful to avoid tedious loop errors.

5. Properly using While Loop

Code:

lst=[1, 2, 3, 4, 4, 6]
index = 0
while index < len(lst):
    print(lst[index])
    index += 1

Output:

1
2
3
4
4
6

Explanation:

Iterating through a while loop can be tricky sometimes. We first have declared the list with random elements and a variable with an integer value of 0. This is because the indexing starts from 0 in Python.

In the condition for the while loop, we’ve stated that the value of the index should be always less than the length of the list. Then we increment the value of the index by 1 in every loop. This creates perfect sync between the 0 and maximum value of the index to avoid any IndexErrors.

6+. Properly using For Loop

Code:

lst=[1, 2, 3, 4, 4, 6]
for i in range(len(lst)):
    print(lst[i])

Output:

1
2
3
4
4
6

Explanation:

Creating a proper for loop is an easy task, especially in python. Use the range() function to iterate the value from 0 to length-1 and close the loop thereafter.

Exceptions are a great way of knowing what error you encounter in the program. Moreover, you can use the try-except blocks to avoid these errors explicitly. The following example will help you to understand –

Code:

lst=[1, 2, 3, 4, 4, 6]
try:
    for i in range(0,len(lst)+1):
        print(lst[i])
except IndexError:
    print("Index error reached")

Output:

1
2
3
4
4
6
Index error reached

Explanation:

In the above example, the value of ‘i’ ranges from 0 to the length of the list. At the very end of its value, it’ll throw IndexError because the index exceeds the maximum value. As a result, we’ve placed it inside the try block to make sure that we can handle the exception. Then we created an except block which prints whenever an exception is raised. The output can help you understand that the code breaks at its last iteration.

Need a Default Value instead of List Index Out of Range?

Sometimes, we need to initialize variables in such a way that, if an error is raised it’ll get assigned to the default value. This declaration can be achieved by using a try-except block or if statement. The following code will help you understand –

Code:

lst = [1, 2]

# case 1
try:
    value = lst[3]
except IndexError:
    value = "Some default value"

print(value)

# case 2
value = lst[3] if len(lst) > 3 else 'Some default value'

print(value)

Output:

Some default value
Some default value

Explanation:

Case 1, uses the try-except IndexError block to declare the value. As we have used [3] in the index and the length of the list is 2, it’ll execute the except block.

Case 2 uses a simple inline if statement which declares the value if the index is greater than the length of the list.

Must Read:

Python List Length | How to Find the Length of List in Python
How to use Python find() | Python find() String Method
Python next() Function | Iterate Over in Python Using next

Conclusion: Python List Index Out of Range

In day to day programming, list index out of range error is very common. We must make sure that we stay within the range of our list in order to avoid this problem. To avoid it we must check the length of the list and code accordingly.

However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

Happy Pythoning!

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.

Понравилась статья? Поделить с друзьями:
  • Index exceeds matrix dimensions ошибка
  • Indesit w105tx коды ошибок
  • Index 25 size 5 minecraft ошибка
  • Indesit iwud 4105 ошибка h20
  • Indesit nsl 605 коды ошибок