In this tutorial, you’ll learn how all about the Python list index out of range error, including what it is, why it occurs, and how to resolve it.
The IndexError
is one of the most common Python runtime errors that you’ll encounter in your programming journey. For the most part, these these errors are quite easy to resolve, once you understand why they occur.
Throughout this tutorial, you’ll learn why the error occurs and walk through some scenarios where you might encounter it. You’ll also learn how to resolve the error in these scenarios.
The Quick Answer:
Table of Contents
What is the Python IndexError?
Let’s take a little bit of time to explore what the Python IndexError
is and what it looks like. When you encounter the error, you’ll see an error message displayed as below:
IndexError: list index out of range
We can break down the text a little bit. We can see here that the message tells us that the index is out of range. This means that we are trying to access an index item in a Python list that is out of range, meaning that an item doesn’t have an index position.
An item that doesn’t have an index position in a Python list, well, doesn’t exist.
In Python, like many other programming languages, a list index begins at position 0
and continues to n-1
, where n is the length of the list (or the number of items in that list).
This causes a fairly common error to occur. Say we are working with a list with 4 items. If we wanted to access the fourth item, you may try to do this by using the index of 4. This, however, would throw the error. This is because the 4th item actually has the index of 3.
Let’s take a look at a sample list and try to access an item that doesn’t exist:
# How to raise an IndexError
a_list = ['welcome', 'to', 'datagy']
print(a_list[3])
# Returns:
# IndexError: list index out of range
We can see here that the index error occurs on the last item we try to access.
The simplest solution is to simply not try to access an item that doesn’t exist. But that’s easier said than done. How do we prevent the IndexError
from occurring? In the next two sections, you’ll learn how to fix the error from occurring in their most common situations: Python for loops and Python while loops.
Need to check if a key exists in a Python dictionary? Check out this tutorial, which teaches you five different ways of seeing if a key exists in a Python dictionary, including how to return a default value.
Python IndexError with For Loop
You may encounter the Python IndexError
while running a Python for loop. This is particularly common when you try to loop over the list using the range()
function.
Let’s take a look at the situation where this error would occur:
# How to raise an IndexError with a For Loop
a_list = ['welcome', 'to', 'datagy']
for i in range(len(a_list) + 1):
print(a_list[i])
# Returns:
# welcome
# to
# datagy
# Traceback (most recent call last):
# IndexError: list index out of range
The way that we can fix this error from occurring is to simply stop the iteration from occurring before the list runs out of items. The way that we can do this is to change our for loop from going to our length + 1, to the list’s length. When we do this, we stop iterating over the list’s indices before the lengths value.
This solves the IndexError
since it causes the list to stop iterating at position length - 1
, since our index begins at 0, rather than at 1.
Let’s see how we can change the code to run correctly:
# How to prevent an IndexError with a For Loop
a_list = ['welcome', 'to', 'datagy']
for i in range(len(a_list)):
print(a_list[i])
# Returns:
# welcome
# to
# datagy
Now that you have an understanding of how to resolve the Python IndexError
in a for loop, let’s see how we can resolve the error in a Python while-loop.
Want to learn more about Python for-loops? Check out my in-depth tutorial that takes your from beginner to advanced for-loops user! Want to watch a video instead? Check out my YouTube tutorial here.
Python IndexError with While Loop
You may also encounter the Python IndexError
when running a while loop.
For example, it may be tempting to run a while loop to iterate over each index position in a list. You may, for example, write a program that looks like this:
# How to raise an IndexError with a While Loop
a_list = ['welcome', 'to', 'datagy']
i = 0
while i <= len(a_list):
print(a_list[i])
i += 1
# Returns:
# welcome
# to
# datagy
# IndexError: list index out of range
The reason that this program fails is that we iterate over the list one too many times. The reason this is true is that we are using a <=
(greater than or equal to sign). Because Python list indices begin at the value 0, their max index is actually equal to the number of items in the list minus 1.
We can resolve this by simply changing the operator a less than symbol, <
. This prevents the loop from looping over the index from going out of range.
# How to prevent an IndexError with a While Loop
a_list = ['welcome', 'to', 'datagy']
i = 0
while i < len(a_list):
print(a_list[i])
i += 1
# Returns:
# welcome
# to
# datagy
In the next section, you'll learn a better way to iterate over a Python list to prevent the IndexError
.
Want to learn more about Python f-strings? Check out my in-depth tutorial, which includes a step-by-step video to master Python f-strings!
How to Fix the Python IndexError
There are two simple ways in which you can iterate over a Python list to prevent the Python IndexError
.
The first is actually a very plain language way of looping over a list. We don't actually need the list index to iterate over a list. We can simply access its items directly.
# Prevent an IndexError
a_list = ['welcome', 'to', 'datagy']
for word in a_list:
print(word)
# Returns:
# welcome
# to
# datagy
This directly prevents Python from going beyond the maximum index.
Want to learn how to use the Python zip()
function to iterate over two lists? This tutorial teaches you exactly what the zip()
function does and shows you some creative ways to use the function.
But what if you need to access the list's index?
If you need to access the list's index and a list item, then a much safer alternative is to use the Python enumerate()
function.
When you pass a list into the enumerate()
function, an enumerate object is returned. This allows you to access both the index and the item for each item in a list. The function implicitly stops at the maximum index, but allows you to get quite a bit of information.
Let's take a look at how we can use the enumerate()
function to prevent the Python IndexError
.
# Prevent an IndexError with enumerate()
a_list = ['welcome', 'to', 'datagy']
for idx, word in enumerate(a_list):
print(idx, word)
# Returns:
# 0 welcome
# 1 to
# 2 datagy
We can see here that we the loop stops before the index goes out of range and thereby prevents the Python IndexError
.
Check out some other Python tutorials on datagy, including our complete guide to styling Pandas and our comprehensive overview of Pivot Tables in Pandas!
Conclusion
In this tutorial, you learned how to understand the Python IndexError
: list item out of range. You learned why the error occurs, including some common scenarios such as for loops and while loops. You learned some better ways of iterating over a Python list, such as by iterating over items implicitly as well as using the Python enumerate()
function.
To learn more about the Python IndexError
, check out the official documentation here.
from django.contrib import messages
from django.shortcuts import render, redirect
from home.forms import RewardModeLForm
from item.models import Item
from person.models import Person
from .models import Reward, YoutubeVideo
# Create your views here.
def home(request):
my_reward = Reward.objects.all()[:1]
# First Div
last_person_post = Person.objects.all()[:1]
last_item_post = Item.objects.all()[:1]
# 2nd Div
lost_person = Person.objects.filter(person=”L”).all()[:1]
lost_item = Item.objects.filter(category=”L”).all()[:2]
# End 2 div
home_found = Person.objects.all()[:3]
home_item = Item.objects.all()[:3]
videos = YoutubeVideo.objects.all()[:3]
context = {
‘my_reward’: my_reward,
‘lost_person’: lost_person,
‘lost_item’: lost_item,
‘home_found’: home_found,
‘home_item’: home_item,
‘videos’: videos,
}
if last_person_post[0].update > last_item_post[0].update:
context[‘last_post’] = last_person_post
else:
context[‘last_post’] = last_item_post
return render(request, ‘home/home.html’, context)
# Reward Function
def reward(request):
if request.method == ‘POST’:
form = RewardModeLForm(request.POST or None)
if form.is_valid():
instance = form.save(commit=False)
instance.user = request.user
instance.save()
messages.add_message(request, messages.SUCCESS, ‘Reward Updated .’)
return redirect(‘home’)
else:
form = RewardModeLForm()
context = {
‘form’: form,
}
return render(request, ‘home/reward.html’, context)
index out of rage