Register Login

IndexError: list assignment index out of range

Updated Jan 15, 2020

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.


×