Ошибка indexerror list assignment index out of range

The reason for the error is that you’re trying, as the error message says, to access a portion of the list that is currently out of range.

For instance, assume you’re creating a list of 10 people, and you try to specify who the 11th person on that list is going to be. On your paper-pad, it might be easy to just make room for another person, but runtime objects, like the list in python, isn’t that forgiving.

Your list starts out empty because of this:

a = []

then you add 2 elements to it, with this code:

a.append(3)
a.append(7)

this makes the size of the list just big enough to hold 2 elements, the two you added, which has an index of 0 and 1 (python lists are 0-based).

In your code, further down, you then specify the contents of element j which starts at 2, and your code blows up immediately because you’re trying to say «for a list of 2 elements, please store the following value as the 3rd element».

Again, lists like the one in Python usually aren’t that forgiving.

Instead, you’re going to have to do one of two things:

  1. In some cases, you want to store into an existing element, or add a new element, depending on whether the index you specify is available or not
  2. In other cases, you always want to add a new element

In your case, you want to do nbr. 2, which means you want to rewrite this line of code:

a[j]=a[j-2]+(j+2)*(j+3)/2

to this:

a.append(a[j-2]+(j+2)*(j+3)/2)

This will append a new element to the end of the list, which is OK, instead of trying to assign a new value to element N+1, where N is the current length of the list, which isn’t OK.

In python, lists are mutable as the elements of a list can be modified. But if you try to modify a value whose index is greater than or equal to the length of the list then you will encounter an Indexerror: list assignment index out of range.  

Python Indexerror: list assignment index out of range Example

If ‘fruits’ is a list, fruits=[‘Apple’,’ Banana’,’ Guava’]and you try to modify fruits[5] then you will get an index error since the length of fruits list=3 which is less than index asked to modify for which is 5.

Python3

fruits = ['Apple', 'Banana', 'Guava']  

print("Type is", type(fruits))  

fruits[5] = 'Mango'

Output:

Traceback (most recent call last):
 File "/example.py", line 3, in <module>
   fruits[5]='Mango'
IndexError: list assignment index out of range

So, as you can see in the above example, we get an error when we try to modify an index that is not present in the list of fruits.

Python Indexerror: list assignment index out of range Solution

Method 1: Using insert() function

The insert(index, element) function takes two arguments, index and element, and adds a new element at the specified index.

Let’s see how you can add Mango to the list of fruits on index 1.

Python3

fruits = ['Apple', 'Banana', 'Guava']

print("Original list:", fruits)

fruits.insert(1, "Mango")

print("Modified list:", fruits)

Output:

Original list: ['Apple', 'Banana', 'Guava']
Modified list: ['Apple', 'Mango', 'Banana', 'Guava']

It is necessary to specify the index in the insert(index, element) function, otherwise, you will an error that the insert(index, element) function needed two arguments.

Method 2: Using append()

The append(element) function takes one argument element and adds a new element at the end of the list.

Let’s see how you can add Mango to the end of the list using the append(element) function.

Python3

fruits = ['Apple', 'Banana', 'Guava']

print("Original list:", fruits)

fruits.append("Mango")

print("Modified list:", fruits)

Output:

Original list: ['Apple', 'Banana', 'Guava']
Modified list: ['Apple', 'Banana', 'Guava', 'Mango']

Last Updated :
04 Jan, 2022

Like Article

Save Article

IndexError: list assignment index out of range

List elements can be modified and assigned new value by accessing the index of that element. But if you try to assign a value to a list index that is out of the list’s range, there will be an error. You will encounter an IndexError list assignment index out of range. Suppose the list has 4 elements and you are trying to assign a value into the 6th position, this error will be raised.

Example:

list1=[]
for i in range(1,10):
    list1[i]=i
print(list1)

Output: 

IndexError: list assignment index out of range

In the above example we have initialized a “list1“ which is an empty list and we are trying to assign a value at list1[1] which is not present, this is the reason python compiler is throwing “IndexError: list assignment index out of range”.

IndexError: list assignment index out of range

We can solve this error by using the following methods.

Using append()

We can use append() function to assign a value to “list1“, append() will generate a new element automatically which will add at the end of the list.

Correct Code:

list1=[]
for i in range(1,10):
    list1.append(i)
print(list1)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

In the above example we can see that “list1” is empty and instead of assigning a value to list, we append the list with new value using append() function.

Using insert() 

By using insert() function we can insert a new element directly at i’th position to the list.

Example:

list1=[]
for i in range(1,10):
    list1.insert(i,i)
print(list1)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

In the above example we can see that “list1” is an empty list and instead of assigning a value to list, we have inserted a new value to the list using insert() function.

Example with While loop

num = []
i = 1
while(i <= 10):
num[i] = I
i=i+1
 
print(num)

Output:

IndexError: list assignment index out of range

Correct example:

num = []
i = 1
while(i <= 10):
    num.append(i)
    i=i+1
 
print(num)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Conclusion:

Always check the indices before assigning values into them. To assign values at the end of the list, use the append() method. To add an element at a specific position, use the insert() method.

An IndexError is nothing to worry about. It’s an error that is raised when you try to access an index that is outside of the size of a list. How do you solve this issue? Where can it be raised?

In this article, we’re going to answer those questions. We will discuss what IndexErrors are and how you can solve the “list assignment index out of range” error. We’ll walk through an example to help you see exactly what causes this error.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

Without further ado, let’s begin!

The Problem: indexerror: list assignment index out of range

When you receive an error message, the first thing you should do is read it. An error message can tell you a lot about the nature of an error.

Our error message is: indexerror: list assignment index out of range.

IndexError tells us that there is a problem with how we are accessing an index. An index is a value inside an iterable object, such as a list or a string.

The message “list assignment index out of range” tells us that we are trying to assign an item to an index that does not exist.

In order to use indexing on a list, you need to initialize the list. If you try to assign an item into a list at an index position that does not exist, this error will be raised.

An Example Scenario

The list assignment error is commonly raised in for and while loops.

We’re going to write a program that adds all the cakes containing the word “Strawberry” into a new array. Let’s start by declaring two variables:

cakes = ["Strawberry Tart", "Chocolate Muffin", "Strawberry Cheesecake"]
strawberry = []

The first variable stores our list of cakes. The second variable is an empty list that will store all of the strawberry cakes. Next, we’re going to write a loop that checks if each value in “cakes” contains the word “Strawberry”.

for c in range(0, len(cakes)):
	if "Strawberry" in cakes[c]:
		strawberry[c] = cakes[c]

print(strawberry)

If a value contains “Strawberry”, it should be added to our new array. Otherwise, nothing will happen. Once our for loop has executed, the “strawberry” array should be printed to the console. Let’s run our code and see what happens:

Traceback (most recent call last):
  File "main.py", line 6, in <module>
	strawberry[c] = cakes[c]
IndexError: list assignment index out of range

As we expected, an error has been raised. Now we get to solve it!

The Solution

Our error message tells us the line of code at which our program fails:

The problem with this code is that we are trying to assign a value inside our “strawberry” list to a position that does not exist.

When we create our strawberry array, it has no values. This means that it has no index numbers. The following values do not exist:

strawberry[0]
strawberry[1]
…

We are trying to assign values to these positions in our for loop. Because these positions contain no values, an error is returned.

We can solve this problem in two ways.

Solution with append()

First, we can add an item to the “strawberry” array using append():

cakes = ["Strawberry Tart", "Chocolate Muffin", "Strawberry Cheesecake"]
strawberry = []

for c in range(0, len(cakes)):
	if "Strawberry" in cakes[c]:
		strawberry.append(cakes[c])

print(strawberry)

The append() method adds an item to an array and creates an index position for that item. Let’s run our code: [‘Strawberry Tart’, ‘Strawberry Cheesecake’].

Our code works!

Solution with Initializing an Array

Alternatively, we can initialize our array with some values when we declare it. This will create the index positions at which we can store values inside our “strawberry” array.

To initialize an array, you can use this code:

This will create an array with 10 empty values. Our code now looks like this:

cakes = ["Strawberry Tart", "Chocolate Muffin", "Strawberry Cheesecake"]
strawberry = [] * 10

for c in range(0, len(cakes)):
	if "Strawberry" in cakes[c]:
		strawberry.append(cakes[c])

print(strawberry)

Let’s try to run our code:

['Strawberry Tart', 'Strawberry Cheesecake']

Our code successfully returns an array with all the strawberry cakes.

This method is best to use when you know exactly how many values you’re going to store in an array.

Venus profile photo

«Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!»

Venus, Software Engineer at Rockbot

Our above code is somewhat inefficient because we have initialized “strawberry” with 10 empty values. There are only a total of three cakes in our “cakes” array that could possibly contain “Strawberry”. In most cases, using the append() method is both more elegant and more efficient.

Conclusion

IndexErrors are raised when you try to use an item at an index value that does not exist. The “indexerror: list assignment index out of range” is raised when you try to assign an item to an index position that does not exist.

To solve this error, you can use append() to add an item to a list. You can also initialize a list before you start inserting values to avoid this error.

Now you’re ready to start solving the list assignment error like a professional Python developer!

The IndexError is a common error that occurs in Python when you try to access an index that is out of range for a list. This error can occur when you try to assign a value to an index that does not exist in the list. In this tutorial, we will discuss how to fix the IndexError list assignment index out of range in Python.

how to fix list assignment index out of range error

Understanding the Error

Before we dive into the solution, let’s first understand what causes the IndexError list assignment index out of range error. This error occurs when you try to assign a value to an index that does not exist in the list. For example, consider the following code:

my_list = [1, 2, 3]
my_list[3] = 4

Output:

---------------------------------------------------------------------------

IndexError                                Traceback (most recent call last)

Cell In[1], line 2
      1 my_list = [1, 2, 3]
----> 2 my_list[3] = 4

IndexError: list assignment index out of range

In the above code, we are trying to assign the value 4 to the index 3 of the my_list list. However, the my_list list only has three elements, so the index 3 does not exist. This results in the IndexError list assignment index out of range error.

Fixing the Error

To fix the IndexError list assignment index out of range error, you need to make sure that the index you are trying to access or assign a value to exists in the list. You can use an if statement to check if the index exists in the list.

Note that Python sequences also allow negative indexing so be mindful of this when checking if an index exists in a list or not. Let’s look at an example.

# create a list
my_list = [1, 2, 3]
# index to assign the value
index = 3
# check if the index exits, if yes, then assign the value
if -len(my_list) <= index < len(my_list):
    # perform the assignment operation
    my_list[3] = 4
else:
    print("Assingnment index is out of range")

Output:

Assingnment index is out of range

Note that if you’re sure that the given index is not negative, you can just check if the index lies in the range 0 to the length of the list using index < len(my_list).

If your end goal is to add an element to a list, you can instead use the list append() or insert() functions.

The append() method adds an element to the end of the list, so you don’t have to worry about the index. For example:

my_list = [1, 2, 3]
my_list.append(4)
print(my_list)

Output:

[1, 2, 3, 4]

Here, we added the element 4 to the end of the list and we didn’t need to provide an index.

If you need to add an element to a specific index in the list, you can use the insert() method. The insert() method takes two arguments: the index where you want to insert the element and the element itself.

my_list = [1, 2, 3]
# insert the element 4 at index 3
my_list.insert(3, 4)
print(my_list)

Output:

[1, 2, 3, 4]

In this code, we are using the insert() method to insert the value 4 at the index 3 of the my_list list. Since we are inserting the element at a specific index, the IndexError list assignment index out of range error will be avoided.

Conclusion

The IndexError list assignment index out of range error occurs when you try to assign a value to an index that does not exist in the list. To fix this error, you need to make sure that the index you are trying to access or assign a value to exists in the list. You can do this by checking the length of the list. If you want to add values to a list, you can use the append() method to add elements to the end of the list, or the insert() method to insert elements at a specific index.

You might also be interested in –

  • Understand and Fix IndexError in Python
  • Python List Append, Extend and Insert
  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

    View all posts

  • Ошибка index is out of date
  • Ошибка incorrect syntax near the keyword from
  • Ошибка increased emissions на бмв
  • Ошибка incorrect syntax near limit
  • Ошибка incorrect table name