How to Solve IndexError: List Assignment Index Out of Range in Python

Updated onbyAlan Morel
How to Solve IndexError: List Assignment Index Out of Range in Python

In Python, you will get an error when you try to assign an index in a list that is out of its range.

This makes sense because lists in Python, like arrays in other langauges, have a set length, and when you exceed the length of the list, you will get an error.

In this post, we'll learn how to avoid the IndexError: list assignment index out of range error.

How to avoid the IndexError error

As mentioned before, this error appears when the index you try to assign to is out of the range of the list.

Let's look at an example code that will result in the error:

PYTHON
input = [1, 2, 3, 4, 5] output = [] output[0] = input[3] print(output)

If you run this code you will get the following result:

BASH
Traceback (most recent call last): File "<string>", line 4, in <module> IndexError: list assignment index out of range

This makes sense because on line 4, we are trying to assign the value of the item at index 3 to the item at index 0. However, when we do output = [], we are creating a brand new list that is empty.

An empty list means the list also has a length of 0, meaning it doesn't have space for any items, even at index 0.

We have two options to avoid this error, the first is to just use append. This will properly add the item to the list, and it will not result in an error.

PYTHON
input = [1, 2, 3, 4, 5] output = [] output.append(input[3]) print(output)
BASH
[4]

The other fix is to just allocate enough space for the output list:

PYTHON
input = [1, 2, 3, 4, 5] output = [0] * len(input) output[0] = input[3] print(output)
BASH
[4, 0, 0, 0, 0]

In this example, we created a list the same length as the length of the input list, and then assigned the value of the item at index 3 to the item at index 0. Because the two lists are now the same size, we can access all the same indexes without error.

Conclusion

In this post, we learned how to avoid the IndexError: list assignment index out of range error.

We can avoid it by using the append method to add items to the list, or by allocating enough space for the list.

Hopefully, you've found this post helpful! Happy coding!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.