IndexError: list assignment index out of range error.
Elements of a python list have numeric indexes with first element having index 0, second element with index 1.
Last element of the list has an index equal to one less than the length of the list. Thus, if a list has 5 elements, then the index of last element will have an index 4.
Values can be assigned to a list using this index or position using below syntax.
list_name[index] = value
If you try to assign value to an index which is greater than,
- the maximum index or the index of last list element, or
- length of list – 1
then this error will be raised.
Remember that python list supports negative indexing as well. This means that if you start from right to left then elements will have negative indexes starting from -1.
If you try to assign a value to a negative index which is greater than the index of last element from right, then also you will get the same error.
Below is a python example which creates a list of 5 elements. It then gets the length of this list using len() function and assigns a value to an index which is greater than this length.
# define a list numbers = [1, 2, 3, 4, 5, 6] length = len(numbers) numbers[length+2] = 20
This program raises the following error
numbers[length+2] = 20
IndexError: list assignment index out of range
Similarly, if you use assign an item at negative index greater than the index of last element from right, same error will be raised as shown below.
# define a list numbers = [1, 2, 3, 4, 5, 6] length = len(numbers) # higher negative index negative_index = length - (length *2) # IndexError numbers[length] = 20
Other scenario
This error may also be raised when you initialize an empty list and try to add elements to it by assigning them to indexes. Example,
# create an empty list numbers = [] for num in range(10): # assign list elements numbers[num] = num
This code example initializes an empty list and uses a for loop to add elements to a list directly by assigning to index. It also raises below error
numbers[num] = num
IndexError: list assignment index out of range
Following ways can be used to avoid list assignment index out of range error in python.
1. Try not to use list assignment at index. Use index assignment only when you are sure that the index lies between the range of list element indexes or it is lesser than the length of list.
2. Use append() method
For adding elements to a list, such as in the latter example above, use append() method of python list.
Thus, for adding elements to a list in a loop, following method can be used.
# create an empty list numbers = [] for num in range(10): # append list elements numbers.append(num) print('List is:',numbers)
which works fine and prints
List is: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Hope the article was useful.