Fix IndexError: list assignment index out of range in Python

In today’s Python automation tutorial we will learn how to troubleshoot index errors that occur when assigning new elements into Python lists. These errors typically occur when we try to add a list element at an index that doesn’t yet exist in the list.

In a nutshell, the safest way to add an item to a list is using the append list method, which will ensure you avoid this error at the first place.

IndexError: list assignment index out of range in Python

Problem

In order to reproduce the error, you can consider the following Python3 code that you can run on every Python Editor such as PyCharm, VS Code, Jupyter etc:

lang_lst = ['Python', 'R', 'Java', 'Go', 'C']

lang_lst[5] = 'Javascript'

print (lang_lst)

This will return the index out of range error.

Solution

The reason is that our list (array) contains 5 elements. Hence the index of the latest element is 4. As we are trying to assign an element with a higher index we get the index out of range error.

The solution is to use the append list function:

lang_lst = ['Python', 'R', 'Java', 'Go', 'C']
lang_lst.append('Javascript')

print ("Our list elements are:" +str (lang_lst))
print ("Our list lenghts is: " + str(len(lang_lst)))

This returns the following:

Our list elements are:['Python', 'R', 'Java', 'Go', 'C', 'Javascript']
Our list lenghts is: 6

Assigning from a Python dictionary to a list

Problem

Consider the follow code that loops through a dictionary key value pairs and assign to a list:

lang_dict = { 1:'Python', 2:'R', 3: 'Julia', 4: 'Go'}
lang_lst = []

for key, value in lang_dict.items():
 lang_lst[key] = value


print ("Our list elements are:" +str (lang_lst))


This will return the index out of range error.

Solution

We can use the list append function:

lang_dict = { 1:'Python', 2:'R', 3: 'Julia', 4: 'Go'}
lang_lst = []

for key, value in lang_dict.items():
 lang_lst.append(value)

print ("Our list elements are:" +str (lang_lst))

You can use the list insert function to add single elements, or etend, if you would like to append multiple elements.

Suggested learning