In this Python tutorial, we will see how to fix IndexError List out of Range in Python using several different ways with illustrative examples.
A list in Python is a built-in data type that can be used to store a collection of items. It is equivalent to arrays in other programming languages but with more functionality. For instance, let’s create a list of the 5 most populous states in the USA
states = ['California', 'Texas', 'Florida', 'New York', 'Pennsylvania']
The state ‘California’ can be accessed with states, ‘Texas’ with states, and so forth.
The Output is:
What is IndexError List out of Range Error in Python
As we all know, Python List is indexed, and all the items in the list have their index number and are accessed using the index number. The index is of two types:
- Positive Index: The first item is assigned with a 0 index number and so on.
- Negative Index: The last item is assigned with a -1 index number and so on, moving backward.
Python IndexError-List out of Range is a common type of error that many programmers come across. This error occurs when a program attempts to access an item at an index that does not exist in the given Python list.
In the above example, the state’s list has 5 elements, so the valid indices are 0 through 4. If we attempt to access states or any index greater than 4, Python will throw an ‘IndexError-list index out of range’ error.
states = ['California', 'Texas', 'Florida', 'New York', 'Pennsylvania'] print(states)
The output is:
This error message is Python’s way of telling us that we’re trying to access a non-existent position in our list. Index 10 in our state’s list is out of the range of valid indices (0-4).
Fix IndexError List out of Range error in Python
There can be many different ways to fix IndexError in Python, let’s explore them one by one with illustrative examples. They are:
- Check the Length of the List
- Use Exception Handling: try-except
Method-1: Fix IndexError list out of Range Error in Python By checking the length of the list
One simple strategy is to always check the length of the Python list before trying to access an item. We can do this using the built-in len() function in Python, which returns the number of items in a list.
For instance: Consider a Python list of the top 5 NBA teams based on their all-time win-loss record percentages:
teams = ['San Antonio Spurs', 'Los Angeles Lakers', 'Boston Celtics', 'Oklahoma City Thunder', 'Utah Jazz'] i = int(input('Enter the index number of the item you want to access: ')) if len(teams) >= i: print(teams[i]) else: print("Index is out of range")
The output is: firstly he will ask for the index number of the item and then will print the result accordingly,
Enter the index number of the item you want to access: 10 Index is out of range
In this case, Python will print “Index is out of range” instead of throwing an error, because the length of teams is not greater than 5. This way we can check the length of the list and fix IndexError list out of range in Python.
Method-2: Fix IndexError list out of Range Error in Python by using Exception Handling: try-except
Another strategy is to use Python try/except blocks to catch and handle the IndexError exception. Here’s an example let’s assume we have a Python list of the Great Lakes, and we try to access an index that doesn’t exist:
great_lakes = ['Superior', 'Michigan', 'Huron', 'Erie', 'Ontario'] try: print(great_lakes) except IndexError: print("That lake does not exist in the Great Lakes list")
The output is: This code attempts to print great_lakes. If this results in an IndexError, Python will instead print “That lake does not exist in the Great Lakes list”.
That lake does not exist in the Great Lakes list
This way we can use Exception handling to fix the IndexError list index out of range in Python .
In conclusion, understanding list indices in Python and the common ‘IndexError list index out of range‘ error is crucial when manipulating lists in our code. By carefully checking our indices and employing simple exception-handling strategies, we can prevent or gracefully handle this error.
You may like to read:
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.