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
- Create an RSS Reader in Node
- Getting Started with Electron
- How to Serve Static Files with Nginx and Docker
- How to Set Up Cron Jobs in Linux
- How to deploy a Deno app using Docker
- Getting Started with Deno
- How to deploy an Express app using Docker
- Getting User Location using JavaScript's Geolocation API
- Learn how to build a Slack Bot using Node.js
- Using Push.js to Display Web Browser Notifications
- Getting Started with Vuex: Managing State in Vue