How to Solve IndexError: List Assignment Index Out of Range in Python
Table of Contents
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:
PYTHONinput = [1, 2, 3, 4, 5]
output = []
output[0] = input[3]
print(output)
If you run this code you will get the following result:
BASHTraceback (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.
PYTHONinput = [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:
PYTHONinput = [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!
- Getting Started with TypeScript
- Managing PHP Dependencies with Composer
- Getting Started with Svelte
- Create an RSS Reader in Node
- Best Visual Studio Code Extensions for 2022
- How to deploy a Deno app using Docker
- Getting Started with Deno
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Learn how to build a Slack Bot using Node.js
- Getting Started with React
- Setting Up Stylus CSS Preprocessor
- Setting Up a Local Web Server using Node.js