IndexError List Assignment Index Out of Range Python

An IndexError exception is generally raised when the index issued is out of range.

In particular, “IndexError: list assignment index out of range” is raised when we attempt to assign a value to an index that is out of range (does not exist).

Figure 1: A list with 4 values. Python is a zero-based indexing language; that is, the index starts with 0 for the first element, index 1 for the second element, and so on. You can also use reverse indexing starting with -1 for the last item (Source: Author).

Reproducing the Error

Output:

[1, 4, 9, 6]
IndexError: list assignment index out of range

lst[2] = 9 assigned index 2 (the third value), the value 9 without an error because lst has 4 values (indices 0, 1, 2, and 3).

lst[7]=11 leads to an “IndexError: list assignment index out of range” error because lst does not have index 7. The list ends with index 3.

Solutions to the Error

Solution 1: Using the <list>.append(<value>)

Use this method if you need to add an item to the end of the list. This prevents us from assigning a value to an index that does not exist.

Output:

[1, 4, 5, 6, 11]

Solution 2: Using if-condition

In this case, we want to check if the index is within the range of the list. If the index is within the range, we assign the value we want; otherwise, we do something else.

Output:

index 7 is out of range

In the above case, we have avoided the “IndexError: list assignment index out of range” error by using the if-condition.

Solution 3: Using a try-except statement

In this method, we attempt to assign a value to a given index, and if that results in IndexError, we do something else.

Output:

list assignment index out of range
[1, 4, 5, 6, 11]

lst[9]=11 resulted in IndexError, then we resorted to appending the value 11 to lst.

Solution 4: Using the list.insert() function

The <list>.insert(<idx>, <value>) inserts <value> to the list at index <idx>. If the index provided is out of range, the value is inserted as the last element in the list.

Output:

[1, 2, 3, 4, 5, 'out of range value']
[1, 2, 3, 'within range', 4, 5, 'out of range value']

Conclusion

The exception IndexError: List Assignment Index Out of Range Python occurs when we try to assign a value to a list at an index that is out of range. In this article, we propose the best solution is to insert the element at the end of the list using the list.append() method.

Other solutions discussed included if-condition to check if the index supplied is within range, try-except to catch IndexError exception, and list.insert() method to insert value at an index (if out of range, the element is appended as the last item in the list).