
- Learn Python
- Python Lists
- Python Dictionaries
- Python Strings
- Python Functions
- Learn Pandas & NumPy
- Pandas Tutorials
- Numpy Tutorials
- Learn Data Visualization
- Python Seaborn
- Python Matplotlib

Python IndexError: List Index Out of Range Error Explained
- November 15, 2021 December 19, 2022

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:
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 4 th 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:
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:
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:
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:
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.
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.
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 .
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 !
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 .
1 thought on “Python IndexError: List Index Out of Range Error Explained”
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
Leave a Reply Cancel reply
Your email address will not be published. Required fields are marked *
Save my name, email, and website in this browser for the next time I comment.
- Free Python 3 Course
- Control Flow
- Exception Handling
- Python Programs
- Python Projects
- Python Interview Questions
- Python Database
- Data Science With Python
- Machine Learning with Python
- Write an Interview Experience
- Share Your Campus Experience
- How to Fix: Invalid value encountered in true_divide
- How to Fix: ValueError: Trailing data?
- How to Fix: TypeError: ‘numpy.float’ object is not callable?
- How to Fix: RuntimeWarning: Overflow encountered in exp
- How to Fix: ValueError: Operands could not be broadcast together with shapes?
- Filter Python list by Predicate in Python
- How to Fix: if using all scalar values, you must pass an index
- How to Fix: columns overlap but no suffix specified
- Internal working of list in Python
- How to Fix: NameError name ‘pd’ is not defined
- How to Replace Values in a List in Python?
- How to Fix: Can only compare identically-labeled series objects
- Python Indexerror: list assignment index out of range Solution
- How to Fix: ValueError: All arrays must be of the same length
- How to Fix: Length of values does not match length of index
- How to Fix: ValueError: cannot convert float NaN to integer
- How to Fix: ‘numpy.ndarray’ object has no attribute ‘index’
- Python list() Function
- How to Fix: TypeError: no numeric data to plot
- How to Fix: NameError name ‘np’ is not defined
- Adding new column to existing DataFrame in Pandas
- Python map() function
- Read JSON file using Python
- How to get column names in Pandas dataframe
- Taking input in Python
- Read a file line by line in Python
- Python Dictionary
- Iterate over a list in Python
- Enumerate() in Python
- Reading and Writing to text files in Python
Python List Index Out of Range – How to Fix IndexError
In Python, the IndexError is a common exception that occurs when trying to access an element in a list, tuple, or any other sequence using an index that is outside the valid range of indices for that sequence. List Index Out of Range Occur in Python when an item from a list is tried to be accessed that is outside the range of the list. Before we proceed to fix the error, let’s discuss how indexing work in Python .
What Causes an IndexError in Python
- Accessing Non-Existent Index: When you attempt to access an index of a sequence (such as a list or a string) that is out of range, an Indexerror is raised. Sequences in Python are zero-indexed, which means that the first element’s index is 0, the second element’s index is 1, and so on.
- Empty List: If you try to access an element from an empty list, an Indexerror will be raised since there are no elements in the list to access.
Example: Here our list is 3 and we are printing with size 4 so in this case, it will create a list index out of range.
Similarly, we can also get an Indexerror when using negative indices.
How to Fix IndexError in Python
- Check List Length: It’s important to check if an index is within the valid range of a list before accessing an element. To do so, you can use the function to determine the length of the list and make sure the index falls within the range of 0 to length-1.
- Use Conditional Statements: To handle potential errors, conditional statements like “if” or “else” blocks can be used. For example, an “if” statement can be used to verify if the index is valid before accessing the element. if or try-except blocks to handle the potential IndexError . For instance, you can use a if statement to check if the index is valid before accessing the element.
How to Fix List Index Out of Range in Python
Let’s see some examples that showed how we may solve the error.
- Using Python range()
- Using Python Index()
- Using Try Except Block
Python Fix List Index Out of Range using Range()
The range is used to give a specific range, and the Python range() function returns the sequence of the given number between the given range.
Python Fix List Index Out of Range u sing Index()
Here we are going to create a list and then try to iterate the list using the constant values in for loops.
Reason for the error – The length of the list is 5 and if we are an iterating list on 6 then it will generate the error.
Solving this error without using Python len() or constant Value: To solve this error we will take the index of the last value of the list and then add one then it will become the exact value of length.
Python Fix List Index Out of Range using Try Except Block
If we expect that an index might be out of range, we can use a try-except block to handle the error gracefully.
Please Login to comment...
Improve your coding skills with practice.
List Index Out of Range – Python Error Message Solved
In this article you'll see a few of the reasons that cause the list index out of range Python error.
Besides knowing why this error occurs in the first place, you'll also learn some ways to avoid it.
Let's get started!
How to Create a List in Python
To create a list object in Python, you need to:
- Give the list a name,
- Use the assignment operator, = ,
- and include 0 or more list items inside square brackets, [] . Each list item needs to be separated by a comma.
For example, to create a list of names you would do the following:
The code above created a list called names that has four values: Kelly, Nelly, Jimmy, Lenny .
How to Check the Length of a List in Python
To check the length of a list in Python, use Python's build-in len() method.
len() will return an integer, which will be the number of items stored in the list.
There are four items stored in the list, therefore the length of the list will be four.
How to Access Individual List Items in Python
Each item in a list has its own index number .
Indexing in Python, and most modern programming languages, starts at 0.
This means that the first item in a list has an index of 0, the second item has an index of 1, and so on.
You can use the index number to access the individual item.
To access an item in a list using its index number, first write the name of the list. Then, inside square brackets, include the intiger that corresponds with the item's index number.
Taking the example from earlier, this is how you would access each item inside the list using its index number:
You can also use negative indexing to access items inside lists in Python.
To access the last item, you use the index value of -1. To acces the second to last item, you use the index value of -2.
Here is how you would access each item inside a list using negative indexing:
Why does the Indexerror: list index out of range error occur in Python?
Using an index number that is out of the range of the list.
You'll get the Indexerror: list index out of range error when you try and access an item using a value that is out of the index range of the list and does not exist.
This is quite common when you try to access the last item of a list, or the first one if you're using negative indexing.
Let's go back to the list we've used so far.
Say I want to access the last item, "Lenny", and try to do so by using the following code:
Generally, the index range of a list is 0 to n-1 , with n being the total number of values in the list.
With the total values of the list above being 4 , the index range is 0 to 3 .
Now, let's try to access an item using negative indexing.
Say I want to access the first item in the list, "Kelly", by using negative indexing.
When using negative indexing, the index range of a list is -1 to -n , where -n the total number of items contained in the list.
With the total number of items in the list being 4 , the index range is -1 to -4 .
Using the wrong value in the range() function in a Python for loop
You'll get the Indexerror: list index out of range error when iterating through a list and trying to access an item that doesn't exist.
One common instance where this can occur is when you use the wrong integer in Python's range() function.
The range() function typically takes in one integer number, which indicates where the counting will stop.
For example, range(5) indicates that the counting will start from 0 and end at 4 .
So, by default, the counting starts at position 0 , is incremented by 1 each time, and the number is up to – but not including – the position where the counting will stop.
Let's take the following example:
Here, the list names has four values.
I wanted to loop through the list and print out each value.
When I used range(5) I was telling the Python interpreter to print the values that are at the positions 0 to 4 .
However, there is no item in position 4.
You can see this by first printing out the number of the position and then the value at that position.
You see that at position 0 is "Kelly", at position 1 is "Nelly", at position 2 is "Jimmy" and at position 3 is "Lenny".
When it comes to position four, which was specified with range(5) which indicates positions of 0 to 4 , there is nothing to print out and therefore the interpreter throws an error.
One way to fix this is to lower the integer in range() :
Another way to fix this when using a for loop is to pass the length of the list as an argument to the range() function. You do this by using the len() built-in Python function, as shown in an earlier section:
When passing len() as an argument to range() , make sure that you don't make the following mistake:
After running the code, you'll again get an IndexError: list index out of range error:
Hopefully this article gave you some insight into why the IndexError: list index out of range error occurs and some ways you can avoid it.
If you want to learn more about Python, check out freeCodeCamp's Python Certification . You'll start learning in an interacitve and beginner-friendly way. You'll also build five projects at the end to put into practice and help reinforce what you learned.
Thanks for reading and happy coding!
Read more posts .
If this article was helpful, tweet it .
Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started
IndexError: list assignment index out of range in Python

Last updated: Jan 29, 2023 Reading time · 10 min

# Table of Contents
- IndexError: list assignment index out of range
- (CSV) IndexError: list index out of range
- sys.argv[1] IndexError: list index out of range
- IndexError: pop index out of range
Make sure to click on the correct subheading depending on your error message.
# IndexError: list assignment index out of range in Python
The Python "IndexError: list assignment index out of range" occurs when we try to assign a value at an index that doesn't exist in the list.
To solve the error, use the append() method to add an item to the end of the list, e.g. my_list.append('b') .

Here is an example of how the error occurs.

The list has a length of 3 . Since indexes in Python are zero-based, the first index in the list is 0 , and the last is 2 .
Trying to assign a value to any positive index outside the range of 0-2 would cause the IndexError .
# Adding an item to the end of the list with append()
If you need to add an item to the end of a list, use the list.append() method instead.

The list.append() method adds an item to the end of the list.
The method returns None as it mutates the original list.
# Changing the value of the element at the last index in the list
If you meant to change the value of the last index in the list, use -1 .

When the index starts with a minus, we start counting backward from the end of the list.
# Declaring a list that contains N elements and updating a certain index
Alternatively, you can declare a list that contains N elements with None values.
The item you specify in the list will be contained N times in the new list the operation returns.
Make sure to wrap the value you want to repeat in a list.
If the list contains a value at the specific index, then you are able to change it.
# Using a try/except statement to handle the error
If you need to handle the error if the specified list index doesn't exist, use a try/except statement.
The list in the example has 3 elements, so its last element has an index of 2 .
We wrapped the assignment in a try/except block, so the IndexError is handled by the except block.
You can also use a pass statement in the except block if you need to ignore the error.
The pass statement does nothing and is used when a statement is required syntactically but the program requires no action.
# Getting the length of a list
If you need to get the length of the list, use the len() function.
The len() function returns the length (the number of items) of an object.
The argument the function takes may be a sequence (a string, tuple, list, range or bytes) or a collection (a dictionary, set, or frozen set).
If you need to check if an index exists before assigning a value, use an if statement.
This means that you can check if the list's length is greater than the index you are trying to assign to.
# Trying to assign a value to an empty list at a specific index
Note that if you try to assign to an empty list at a specific index, you'd always get an IndexError .
You should print the list you are trying to access and its length to make sure the variable stores what you expect.
# Use the extend() method to add multiple items to the end of a list
If you need to add multiple items to the end of a list, use the extend() method.
The list.extend method takes an iterable (such as a list) and extends the list by appending all of the items from the iterable.
The list.extend method returns None as it mutates the original list.
# (CSV) IndexError: list index out of range in Python
The Python CSV "IndexError: list index out of range" occurs when we try to access a list at an index out of range, e.g. an empty row in a CSV file.
To solve the error, check if the row isn't empty before accessing it at an index, or check if the index exists in the list.

Assume we have the following CSV file.
And we are trying to read it as follows.
# Check if the list contains elements before accessing it
One way to solve the error is to check if the list contains any elements before accessing it at an index.
The if statement checks if the list is truthy on each iteration.
All values that are not truthy are considered falsy. The falsy values in Python are:
- constants defined to be falsy: None and False .
- 0 (zero) of any numeric type
- empty sequences and collections: "" (empty string), () (empty tuple), [] (empty list), {} (empty dictionary), set() (empty set), range(0) (empty range).
# Check if the index you are trying to access exists in the list
Alternatively, you can check whether the specific index you are trying to access exists in the list.
This means that you can check if the list's length is greater than the index you are trying to access.
# Use a try/except statement to handle the error
Alternatively, you can use a try/except block to handle the error.
We try to access the list of the current iteration at index 1 , and if an IndexError is raised, we can handle it in the except block or continue to the next iteration.
# sys.argv [1] IndexError: list index out of range in Python
The sys.argv "IndexError: list index out of range in Python" occurs when we run a Python script without specifying values for the required command line arguments.
To solve the error, provide values for the required arguments, e.g. python main.py first second .

I ran the script with python main.py .
The sys.argv list contains the command line arguments that were passed to the Python script.
# Provide all of the required command line arguments
To solve the error, make sure to provide all of the required command line arguments when running the script, e.g. python main.py first second .
Notice that the first item in the list is always the name of the script.
It is operating system dependent if this is the full pathname or not.
# Check if the sys.argv list contains the index
If you don't have to always specify all of the command line arguments that your script tries to access, use an if statement to check if the sys.argv list contains the index that you are trying to access.
I ran the script as python main.py without providing any command line arguments, so the condition wasn't met and the else block ran.
We tried accessing the list item at index 1 which raised an IndexError exception.
You can handle the error or use the pass keyword in the except block.
# IndexError: pop index out of range in Python
The Python "IndexError: pop index out of range" occurs when we pass an index that doesn't exist in the list to the pop() method.
To solve the error, pass an index that exists to the method or call the pop() method without arguments to remove the last item from the list.

The list has a length of 3 . Since indexes in Python are zero-based, the first item in the list has an index of 0 , and the last an index of 2 .
If you need to remove the last item in the list, call the method without passing it an index.
The list.pop method removes the item at the given position in the list and returns it.
You can also use negative indices to count backward, e.g. my_list.pop(-1) removes the last item of the list, and my_list.pop(-2) removes the second-to-last item.
Alternatively, you can check if an item at the specified index exists before passing it to pop() .
This means that you can check if the list's length is greater than the index you are passing to pop() .
An alternative approach to handle the error is to use a try/except block.
If calling the pop() method with the provided index raises an IndexError , the except block is run, where we can handle the error or use the pass keyword to ignore it.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
- IndexError: index 0 is out of bounds for axis 0 with size 0
- IndexError: invalid index to scalar variable in Python
- IndexError: pop from empty list in Python [Solved]
- Replacement index 1 out of range for positional args tuple
- IndexError: string index out of range in Python [Solved]
- IndexError: too many indices for array in Python [Solved]
- IndexError: tuple index out of range in Python [Solved]

Borislav Hadzhiev
Web Developer

Copyright © 2023 Borislav Hadzhiev
- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- Labs The future of collective knowledge sharing
- About the company
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
IndexError: list assignment index out of range in dictionary
I am doing a program to modify the profiles of the windows terminal, and these are in a JSON file. Well I want to put another profile using python (the profile is a dictionary) and I get the following error:
The code is this:
How do I put the dictionary there without an error?
The profiles.json content:
i tryed with datos["profiles"][len(datos["profiles"])].append({"guid":"{"+pguid+"}","name":pname,"commandline":proot}) but dont works
- 1 How about changing len(datos["profiles"]) to len(datos["profiles"]) -1 ? – Mayur Jan 31, 2020 at 19:20
- Can you show was the data of profiles.json file? – Mayur Jan 31, 2020 at 19:20
2 Answers 2
If you’re trying to add a new entry to the end of a list, use .append :
Note that you can construct the whole object all at once in append instead of setting the values one by one.
Python specifications guarantee that this will be a subscript out of range:
or, more simply
Python lists are 0-indexed. For instance, if your list hase 5 elements, the legal indices are 0..4; there is no element 5 .
Instead, try
to get the last element.

- I want to do is add a dictionary, not modify the last one. – URROVA Jan 31, 2020 at 19:31
- How does that relate to my answer? I showed you how to correct the failing line of code. – Prune Jan 31, 2020 at 22:48
- Thank you very much, but I wanted to do something else. What I wanted to do was add a dictionary that represents the profile, not see the last one. When trying to add a dictionary I was wrong, not when trying to get values from it. I already solved it thanks to nneonneo with append. Also thank you very much. – URROVA Jan 31, 2020 at 23:14
Your Answer
Sign up or log in, post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct .
Not the answer you're looking for? Browse other questions tagged python json dictionary terminal or ask your own question .
- The Overflow Blog
- What it’s like being a professional workplace bestie (Ep. 603)
- Journey to the cloud part I: Migrating Stack Overflow Teams to Azure
- Featured on Meta
- Moderation strike: Results of negotiations
- Our Design Vision for Stack Overflow and the Stack Exchange network
- Temporary policy: Generative AI (e.g., ChatGPT) is banned
- Discussions experiment launching on NLP Collective
- Call for volunteer reviewers for an updated search experience: OverflowAI Search
Hot Network Questions
- How much does choice of PhD typically matter for a future career in academia?
- Is this excerpt from an AI-generated answer re Portugal in WWII based on any real events?
- Terminal: How to move files to the last used directory conveniently?
- Stretching left, "inside" and right delimiters
- Convert a Gaussian integer to its positive form
- proof of termination for zip in Lean
- After putting something in my oven, the temperature drops and is super slow to increase back up despite keeping the door shut
- Turned away for medical service at private urgent care due to being enrolled in medicare even with private insurance
- How can I find a list of Chrome's hidden urls with chrome://?
- Indispensable, Essential, "Tool of the trade", "Staple item"
- Entire Perimeter of FPGA Getting Hot - Why?
- Usage of the word "deployment" in a software development context
- Can I be admitted to the US after a two-year overstay 21 years ago?
- Recommendations for study material for mathematical statistics
- Can a company with very large valuation still be hold privately?
- Meaning of "How you get any work done is beyond me"
- Lacunary weight one modular forms
- Why do oil kaleidoscopes only have floating items at the end?
- Are there any more ways to regain spent hit dice?
- How to slow down while maintaining altitude
- How much monthly costs can I expect if I get a kitten or two?
- LVM: Creation difference between CentOS 7 and CentOS 6
- Prism: full spectrum including UV + IR
- Am I considered a non-resident of California?
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

- Documentation
- System Status

- Rollbar Academy

- Software Development
- Engineering Management
- Platform/Ops
- Customer Support
- Software Agency

- Low-Risk Release
- Production Code Quality
- DevOps Bridge
- Effective Testing & QA
How to Fix Python’s “List Index Out of Range” Error in For Loops


Table of Contents
The List Index Out of Range error often occurs when working with lists and for loops. You see, in Python, when you attempt to access an element using an index that lies outside the valid index range of the list, you're essentially telling the program to fetch something that isn't there, resulting in this common error.
It's the interpreter's way of signaling that there's a misalignment in your expectations of the list's size and the actual indices present.
Let’s take a closer look at common ways a for loop can cause List Index Out of Range and how to either avoid it completely or gracefully handle this error when it crops up.
What causes the “List Index Out of Range” error?
As Python uses zero-based indexing, when you try to access an element at an index less than 0 or greater than or equal to the list’s length, Python tells you via this error that the specified index is out of the permissible bounds of the list's length. Here are some common scenarios when this error occurs:
Incorrect loop indexing
If an index used in a loop across a range of indices is greater than the list's length, the error IndexError: list Index Out of Range occurs.
Example: In the below code, the loop runs four times, and on the fourth iteration, my_list[3] is accessed, which doesn’t exist, raising the error.
Changing the list inside the loop
If the list is updated within the loop like removing elements it can cause the loop to go past the updated list length raising the error.
Example: In the below code, the second iteration removes the element, reducing the list’s length to 2, but still, the loop proceeds one more time, raising the error.
Incorrect list length calculation
If you mention the wrong condition inside the for loop, you’ll encounter this error.
Example: In the below code, my_list[3] will be accessed, which doesn’t exist, raising the error.
How to resolve the “List Index Out of Range” error in for loops
Below are some ways to tackle the List Index Out of Range error when working with for loops.
Use enumerate()
You can make use of the enumerate() function to iterate over both the indices and elements of the list simultaneously. This makes sure that you stay within the bounds of the list.
Precalculate the list’s length
Before iterating over a list it’s a good practice to pre-calculate the length of the list.
Handle list modification
Whenever modifying the list inside the loop, it’s better to use a copy of the list or a different data structure to avoid altering the loop’s behavior.
Use try-catch blocks
You can wrap your index access inside a try-catch block to catch the exception and handle it gracefully.
Track, Analyze and Manage Python Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Try it today!
Related Resources

How to Fix IndexError: string index out of range in Python

How to Fix the “List Index Out of Range” Error in Python Split()

How to Fix IndexError in Python
"Rollbar allows us to go from alerting to impact analysis and resolution in a matter of minutes. Without it we would be flying blind."

Start continuously improving your code today.
- eCommerce Consulting
- eCommerce Analytics
- ERP Consulting
- Customer Experience Consulting
- UI/UX Design
- Customer Experience Optimisation
- eCommerce development
- Headless eCommerce
- CMS & Web App development
- SYSTEM Integration & DATA Migration
- Product Information Management
- ERP solution & implemenation
- Service Level Management
- DevOps Cloud
- eCommerce security
- Odoo gold partner
By Industry
- Distribution
- Manufacturing
- Infomation technology
Business Model
- MARKETPLACE ECOMMERCE
Our realized projects

MB Securities - A Premier Brokerage

iONAH - A Pioneer in Consumer Electronics Industry

Emers Group - An Official Nike Distributing Agent

Academy Xi - An Australian-based EdTech Startup
- Market insight

- Ohio Digital
- Onnet Consoulting
The Problem: indexerror: list assignment index out of range
When you receive an error message, the first thing you should do is read it. Because, an error message can tell you a lot about the nature of an error.
indexer message is:
indexerror: list assignment index out of range.
To clarify, IndexError tells us that there is a problem with how we are accessing an index. An index is a value inside an iterable object, such as a list or a string. Then, the message “list assignment index out of range” tells us that we are trying to assign an item to an index that does not exist.
In order to use indexing on a list, you need to initialize the list. Moreover, if you try to assign an item into a list at an index position that does not exist, this error will be raised.
An Example Scenario
The list assignment error is commonly raised in for and while loops.
We’re going to write a program that adds all the cakes containing the word “Strawberry” into a new array. Let’s start by declaring two variables:
To clarify, the first variable stores our list of cakes. The second variable is an empty list that will store all of the strawberry cakes. Then, we’re going to write a loop that checks if each value in “cakes” contains the word “Strawberry”.
If a value contains “Strawberry”, it should be added to our new array. Otherwise, nothing will happen. Once our for loop has executed, the “strawberry” array should be printed to the console. Let’s run our code and see what happens:
As we expected, an error has been raised. Then, we get to solve it.
>>> Read more
- Local variable referenced before assignment: The UnboundLocalError in Python
- Rename files using Python: How to implement it with examples
The solution to list assignment Python index out of range
Our error message tells us the line of code at which our program fails:
To clarify, the problem with this code is that we are trying to assign a value inside our “strawberry” list to a position that does not exist.
When we create our strawberry array, it has no values. To clarify, this means that it has no index numbers. The following values do not exist:
We are trying to assign values to these positions in our for loop. Because these positions contain no values, an error is returned. So, we can solve this problem in two ways.
Solution with append()
Firstly, we can add an item to the “strawberry” array using append():
The append() method adds an item to an array and creates an index position for that item.
Let’s run our code:
The code works!
Solution with Initializing an Array to list assignment Python index out of range
Alternatively, we can initialize our array with some values when we declare it. Because, Tthis will create the index positions at which we can store values inside our “strawberry” array. Therefore, to initialize an array, you can use this code:
This will create an array with 10 empty values. Our code now looks like this:
Let’s try to run the code:
The code successfully returns an array with all the strawberry cakes.
This method is best to use when you know exactly how many values you’re going to store in an array.
The above code is somewhat inefficient because we have initialized “strawberry” with 10 empty values. There are only a total of three cakes in our “cakes” array that could possibly contain “Strawberry”.
To sum up with list assignment python index out of range
IndexErrors are raised when you try to use an item at an index value that does not exist. The “indexerror: list assignment index out of range” is raised when you try to assign an item to an index position that does not exist.
To solve this error, you can use append() to add an item to a list. You can also initialize a list before you start inserting values to avoid this error. So, now you’re ready to start solving the list assignment error like a professional Python developer.
Do you have trouble with contacting a developer? So we suggest you one of the leading IT Companies in Vietnam – AHT Tech . AHT Tech is the favorite pick of many individuals and corporations in the world. For that reason, let’s explore what awesome services which AHT Tech have? More importantly, don’t forget to CONTACT US if you need help with our services .
- code review process , ecommerce web/app development , eCommerce web/mobile app development , fix error , fix python error , list assignment index out of range , python indexerror , web/mobile app development
Our Other Services
- E-commerce Development
- Web Apps Development
- Web CMS Development
- Mobile Apps Development
- Software Consultant & Development
- System Integration & Data Migration
- Dedicated Developers & Testers For Hire
- Remote Working Team
- Offshore Development Center
- Saas Products Development
- Web/Mobile App Development
- Outsourcing
- Hiring Developers
- Digital Transformation
- Advanced SEO Tips

Lastest News

A Comprehensive Guide to SaaS Business Intelligence Software

How CRM Software for Finacial Advisors helps improve ROI

Utilizing Free CRM Software for Insurance Agents for Cost-Saving

Spotlight on Business Intelligence Software Companies

Optimize Customer Strategy with CRM Software for Banks

CRM Software For Real Estate: Boost Efficiency
Tailor your experience
- Success Stories
Copyright ©2007 – 2021 by AHT TECH JSC. All Rights Reserved.

IndexError: list index out of range _ for loop in jsondata
Please have a look into py and json files in the link below: https://filetransfer.io/data-package/2FfG8v0N
How can I modify for loop code in py file to scrape json file completely?
Thanks for all.
Please put your Python program here between triple backticks like this:
Otherwise it is hard to talk about it and we are also lessening the benefit for other readers of this discussion.
Put the complete traceback with the error message here too (also between triple backticks).
If you are able to make the JSON reasonably short and still valid and still making your program fail the same way. Put the JSON here too.
sure, @vbrozik thanks for response. here it’s the wrong loop code i want to fix.
Thank you for showing the code here. The subject of this topic suggests that the program ends with an error. Could you please show the complete error message? Include all the lines of the error message - it is called traceback.
Also how many iterations does the for loop perform before it fails? I.e. how many lines does the print() write? I think it would be easiest if you copy the complete text from your console - including the program invocation, the output (cut out its middle lines, if it is too long) and the error message.
13 lines it performed before it fails. In 14th iteration, there is no game[“E”][8] and game[“E”][9] so it stopped to work. I deleted three objects from print “over, gline, game”. It worked but, then it stopped to work for another object awayteam = game[“O2”] too in another iteration. So for all 11 objects I want the code continue to work even what that object not exists.
It failed at under = game["E"][9]["C"] which is after gline = game["E"][8]["P"] so the list game["E"] of the 14th record must contain the index 8 . Note that Python indexes lists from 0 so game["E"][9] refers to the 10th item of the list.
It looks like you understand what is going on so now you need to:
- Go through the specification of the format of the data you are processing.
- Decide if the missing items are according to the format or not (i.e. the 18july.json file is OK or faulty).
- Fix your program (if the file is OK) and/or decide what you want to do with similar missing fields in your program.
For 3. you have many options - for example:
- Quit with an error - similarly to what does the program do now.
- Replace the incomplete records with special output - e.g. “invalid record”.
- Ignore incomplete records (skip them).
- Replace missing fields with special output - e.g. “N/A”.
File is OK @vbrozik , so I need to fix my program, but I don’t know how to do it. I would prefer Option 4. Missing fields can be replaced as “N/A” Bcuz I want to process whole output in the excel for statistical purposes.
Here is how it can be done (it is a functional code). I will comment it later.
i tried to edit your code for 11 items like this:
but it gave error like this:
you know there are 11 items; Three items (country, league, date) always can be found in json file but rest 8 items can be missing, so they have to be replaced “None” Eight items (homeaway, awayteam, odds1, oddsX, odds2, over, gline, under)
Here is the mistake:
Instead of calling the method get you assign it to the variable. It should probably be json_record.get("A") ?
Now the explanation I promised:
You wrote that you want to process the data. Suitable structure to put data like this together is a class. You can later add methods to the class for some parts of the processing.
These are type annotations. They are not used during the program execution but they are useful as a part of documentation, they can help while writing the program in IDE (like VS Code) and they help to check the program for example using mypy .
Class methods are often used as an alternative initializer of an object. Here we create the object from a JSON structure so I wrote it as a class method. Again there are type annotations which are not necessary:
This will raise KeyError if the key "S" is not present. If you want to allow missing key use json_record.get("S") instead. get() returns None when the key is missing. If the key should be present it is better if the program fails sooner rather than later. It is then easier to analyze the problem.
Here we set the default values because later when the value setting fails we want to have the default there.
The following code I wrote as an example how to handle the situation when the key "E" is missing or when it contains an empty container. If the key should be present, get rid of the if and use for example game_e = json_record["E"] instead.
Here the context manager contextlib.suppress(IndexError) suppresses the exception IndexError . So the code continues when the enclosed statement fails with this exception.
This method defines how the object converts to string when you call str(your_object) . This is done automatically when you do print(your_object) .
This reads the records from the JSON data to a list of Game objects.
Later you will do your processing on this list.
Thanks a lot Vaclav. I have occupied your all day, I’m sorry really. All these detailed explanation you provided for me is really impossible to understand. I’m an idiot. Dismiss further steps, I still couldn’t be able to get even a proper output. I couldn’t modify your code successfully. It is giving an error all the time.
Your program contained just the one mistake. Here it is fixed. I have also removed the type annotations which is an advanced concept.
You should go through some beginner course. You will need it anyway to process the data. Few years ago I used the Sololearn beginner course.
You will learn Python, it just needs to invest the time and start playing with simple problems first.
No @vbrozik , it’s still not solved. here is the output:
as you see, hometeam and awayteam variables not defined properly rest 9 are OK.
please check this once more:
country = jsondata[“Value”][0 ][“CN”] league = jsondata[“Value”][0] [“L”] date = jsondata[“Value”][0] [“S”] hometeam = jsondata[“Value”][0] [“O1”] awayteam = jsondata[“Value”][0] [“O2”]
odds1 = jsondata[“Value”][0] [“E”][0][“C”] oddsX = jsondata[“Value”][0] [“E”][1][“C”] odds2 = jsondata[“Value”][0 ][“E”][2][“C”] over = jsondata[“Value”][0] [“E”][8][“C”] gline = jsondata[“Value”][0] [“E”][8][“P”] under = jsondata[“Value”][0] [“E”][9][“C”]
Compare these two accesses. Your original code:
The new code:
To correspond to your original code you need to use code like this:
Or this one if you want to tolerate missing key "O2" :
IndexError error happens only when accessing lists using a_list[a_index] when the index is out of range. There is no need to suppress it for game.awayteam = game.get["O2"] .
latest code you sent me this:
i dont see any line like this inside it
only this part is problematic in the code
Please read my comments carefully. As I tried to explain in the comment I added the assignment to give the necessary context to the following code. That is what I meant by: “ This statement illustates… ”

Edit: Now I see my horrible mistakes. I have edited my previous post with aim to fix them and improve the readability. Please let me know if my English is still unclear.
The previous post contains the solution. You really should go through a Python introductory course. You need to understand lists, dictionaries etc. to continue working on your program.
If there are specific parts of the code you want me to explain, show them.
Why are you diligently to write these two parts partially? All code all about only 25-30 lines @vbrozik Why don’t you submit fixed final version of whole code ?
It’s not about going to course or taking course. Sorry, but you’re playing with me like you playing with kitten. You don’t intend to help me.
this gives error
this gives error too
this edit gives error too.

Solution for IndexError: list index out of range in python
If you are new to python and wondering what is “ IndexError: list index out of range “, here is the answer. This is a stupid bug in your program that happens when your application tries to access an index that does not exist.
Sometimes it’s very frustrating to figure out where this bug is happening in your program.
An IndexError exception is thrown when the program is trying to access a nonexistent index in a List, Tuple, or String
Python lists are 0-indexed. It means the list in python starts with index 0. If you have 3 elements in python, the last element’s index will be 2 and not 3. If your program tries to access index 3, the compiler will show IndexError: list index out of range .
Take a look at the example below
Please enable JavaScript
From the above example, it is clear that the first element in the list will have index 0 and the last element in the list will have an index len(_list) - 1 . In the above example, we had a list of where this error happened. The same error could also occur with tuple with error: indexerror: tuple index out of range .
if you try to access the non-existing index in a Tuple or String, the compiler will throw the same exception. The wordings would be slightly different in the case of the tuple, the error would be IndexError: tuple index out of range
A common pattern where “indexError: list index out of range” error occurs.
- Checking for the element in the list incorrectly. If you have 3 elements in the list and you are checking to see if the list contains the 4th element, the compiler will throw this error.
In the above example, we are trying to check if there is any value at index 3 using the if statement. Before producing the result for the if statement, the compiler will execute _list[3] and throw the “index out of range” error.
How to fix “indexError: list index out of range”.
The solution to the above problem would be, before accessing the index, to check the length of the list to make sure the index is not out of range .
The other solution could be using enumerate function to iterate through the list.
indexError: list index out of range for loop
Another example, where the program tries to access nonexisting index while iterating through for loop
basically, the above program fails due to the value j in scores being much higher than the length of list scores. So j is not 0, 1, 2, 3, but rather 20, 40, 60, 80.
When the program executes for i in range((0, N[j]) , it looks for the element in scores at index 20, which doesn’t exist, and throws IndexError .
This error is avoidable by selecting the name of the variable wisely. for example:
list index out of range python split
This usually happens when a program tries to access an element from an array generated from the split function. For example, a variable is initialized and assigned a value of the output of the split function , and the split function produces no result.
The program tries to access the first element of the array.
Fixing indexerror: tuple index out of range
Tuple throws the same error when the application tries to access the unavailable index. for example
In the above example, the code is trying to access the fifth element in the tuple which is not available. To fix this kind of problem, you can use the element instead of the index or start with the 0th element.
Solution to Fix the indexerror: tuple index out of range

I am a software engineer with over 10 years of experience in blogging and web development. I have expertise in both front-end and back-end development, as well as database design, web security, and SEO.
Related Posts
Top 5 cross platform mobile development frameworks.

PHP Code To Send Email Using MySQL Database
How to install and configure visual studio code.

List of Best SQL Project Ideas for Beginners
How to list all files in a directory in python.

Computer science projects ideas to build in 2021
![Library Management System Project Design [Step by Step] 6 Library Management System Design [Step by Step]](https://ssiddique.info/wp-content/uploads/2021/01/Library-Management-System-Design-Step-by-Step-1024x512.jpg)
Library Management System Project Design [Step by Step]

16 Fun Python Projects for Beginners and Intermediate programmers
Comments are closed.

IMAGES
VIDEO
COMMENTS
Python error: IndexError: list assignment index out of range Ask Question Asked 14 years, 2 months ago Modified 3 years, 8 months ago Viewed 790 times 2 a= [] a.append (3) a.append (7) for j in range (2,23480): a [j]=a [j-2]+ (j+2)* (j+3)/2 When I write this code, it gives an error like this:
1 Use this: weeknumber = [] for i in range (28): weeknumber.append ( []) for j in range (35)): weeknumber [i].append (pd.Timestamp (date_range [i] [j]).weekofyear) For an explanation of why you get surprising results to your other approach, refer to this answer to your other question Share Improve this answer Follow answered Oct 30, 2020 at 6:25
Python Indexerror: list assignment index out of range Solution Method 1: Using insert () function The insert (index, element) function takes two arguments, index and element, and adds a new element at the specified index. Let's see how you can add Mango to the list of fruits on index 1. Python3 fruits = ['Apple', 'Banana', 'Guava']
November 15, 2021 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.
The message "list assignment index out of range" tells us that we are trying to assign an item to an index that does not exist. In order to use indexing on a list, you need to initialize the list. If you try to assign an item into a list at an index position that does not exist, this error will be raised. An Example Scenario
2 Answers Sorted by: 2 The problem is that ultimately, you appear to be feeding in a list index that is either too small, or too large. According to the error message, the problematic piece of code is self.listOfRows [x - 1] [y - 1] = value. You call it by doing newGrid.setValue (n [k] [0], n [k] [1], List [k]).
Here is my function's code: import random def generate(n): res = [0] x = [0] while x == 0: x[0] = random.randint(0, 9) res = res[0].append(x[0]) for i in range(1, n ...
The index '1' is the second item in the list. In your code, your range(1,anzhalgegner) would start at 1 and increment up to whatever you have set anzhalgegner to be. In your first iteration, your code attempts to assign a value to the list gegner at position 1 - however, the list does not have anything at position 0, meaning it can't assign ...
In Python, the IndexError is a common exception that occurs when trying to access an element in a list, tuple, or any other sequence using an index that is outside the valid range of indices for that sequence. List Index Out of Range Occur in Python when an item from a list is tried to be accessed that is outside the range of the list.
I'm trying to write a program that simulates a lottery game, but when I try to check the user's guesses against the number of guesses on the ticket, I get an error that tells me the "list index is out of range". I think it has something to do with the part of the code where I assign the random digits to "a," "b", "c", etc. But I'm not sure.
I am trying to achieve functionality. It's working should be this way: It takes two lists. Mark some indexes, preferably center few. Both parents switches marked indexes. Other indexes go sequent...
I am trying to delete last 5 elements i.e. '%20' from list arr:- arr = ['A', 't', 'u', 'l', '%20', 'K', 'r', 'i', 's', 'h', 'n', 'a', '%20', 'P', 'a', 't', 'n', 'a ...
1 Answer. This is not allowed in Python; you cannot assign to list indices that aren't already present. (Also, the first index would be 0, not 1 .) You made p an empty list, and thus none of these assignments are allowed. To append a value to the end of a list, regardless of how many elements it already contains, use the .append () method.
You'll get the Indexerror: list index out of range error when you try and access an item using a value that is out of the index range of the list and does not exist. This is quite common when you try to access the last item of a list, or the first one if you're using negative indexing. Let's go back to the list we've used so far.
But I get an error message that says IndexError: list assignment index out of range, referring to the j [k] = l line of code. Why does this occur? How can I fix it? python exception Share Follow edited Oct 11, 2022 at 3:37 Karl Knechtel 62.4k 11 100 153 asked Apr 13, 2011 at 18:01 Vladan 2,793 5 19 15 10
The Python "IndexError: list assignment index out of range" occurs when we try to assign a value at an index that doesn't exist in the list. To solve the error, use the append () method to add an item to the end of the list, e.g. my_list.append ('b'). Here is an example of how the error occurs. main.py
sys.argv is the list of command line arguments passed to a Python script, where sys.argv [0] is the script name itself. It is erroring out because you are not passing any commandline argument, and thus sys.argv has length 1 and so sys.argv [1] is out of bounds. To "fix", just make sure to pass a commandline argument when you run the script, e.g.
0. Python specifications guarantee that this will be a subscript out of range: datos ["profiles"] [len (datos ["profiles"])] or, more simply. my_list [len (my_list)] Python lists are 0-indexed. For instance, if your list hase 5 elements, the legal indices are 0..4; there is no element 5. Instead, try.
20 40 60 Error: list index out of range Index 3 is out of range Track, Analyze and Manage Python Errors With Rollbar Managing errors and exceptions in your code is challenging.
The "indexerror: list assignment index out of range" is raised when you try to assign an item to an index position that does not exist. To solve this error, you can use append() to add an item to a list.
Here is how it can be done (it is a functional code). I will comment it later. from __future__ import annotations import json import contextlib from typing import Any, Mapping class Game: country: str league: str date: int ...
How to fix "indexError: list index out of range". The solution to the above problem would be, before accessing the index, to check the length of the list to make sure the index is not out of range. colors = ["red", "blue", "black"] if len (colors) > 3 and colors [3]: print ("We have color at index 3") else: print ("There is no color at ...