Do My Programming HomeworkDo My Programming Homework

IndexError: list index out of range in Python (8 causes and fixes)

You asked a list for a position it doesn’t have. Here are the 8 usual causes, each with the code that fails, the code that works, and how to tell which one is yours.

DoMyProgrammingHomework.io engineering teamReviewed by Pollen Victory, founderPublished Nov 22, 2026 · 7 min read
A Python script that reads position 3 of a three-item list, and the message IndexError: list index out of range
The short answer
“IndexError: list index out of range” means you asked a list for a position it does not have. A list with 3 items has positions 0, 1 and 2, so asking for position 3 fails. Go to the line in the traceback and print the index and the length of the list just before it. The cause is nearly always a loop that goes one step too far, an empty list, or a list that got shorter while you were looping over it.

Python’s documentation describes this error in one line: “Raised when a sequence subscript is out of range.” The subscript is the number in the square brackets. Out of range means there is no item at that position.

We ran every example below on Python 3.13 before writing it down. The error messages are copied from those runs.

Which positions exist

Python counts from 0. Its documentation calls s[i] the “ith item of s, origin 0”. So the last position is always one less than the length.

Negative numbers count from the end. The documentation says a negative index “is relative to the end of sequence”. Position -1 is the last item.

What each index returns for scores = [90, 85, 70]
You writeYou getWhy
scores[0]90The first item
scores[2]70The last item: length 3, minus 1
scores[3]IndexErrorThere is no fourth item
scores[-1]70The last item, counted from the end
scores[-3]90The first item, counted from the end
scores[-4]IndexErrorToo far back
scores[3:][]Slices never raise this error

The last row surprises people. The Python tutorial says “out of range slice indexes are handled gracefully when used for slicing”. A slice that reaches too far just returns fewer items, or an empty list.

How to read the traceback

What Python printstext
Traceback (most recent call last):
  File "scores.py", line 3, in <module>
    print(scores[i])
          ~~~~~~^^^
IndexError: list index out of range

Read it from the bottom. The last line names the error. The lines above it give the file and the line number, and recent versions of Python underline the exact brackets that failed. That is where to look. It is not always where the mistake is: the index was usually set to a bad value a few lines earlier.

The 8 causes

The 8 causes at a glance
CauseThe line that failsThe fix
1. The loop goes one step too farrange(len(scores) + 1)range(len(scores)), or loop over the items
2. The length used as the last positionscores[len(scores)]scores[-1]
3. Looking at the next itemscores[i + 1]Stop one step early
4. The list is emptyscores[0]Check the list first
5. Deleting while loopingdel scores[i] inside the loopBuild a new list
6. Assigning to a position that doesn’t existsquares[i] = ... on an empty listappend
7. The input is shorter than you expectedparts[2], sys.argv[1]Check the length first
8. Rows of different lengthsgrid[row][col]Loop over each row’s own items

1. The loop goes one step too far

Fails: i reaches 3, and there is no scores[3]python
scores = [90, 85, 70]
for i in range(len(scores) + 1):
    print(scores[i])
Passes: loop over the items themselvespython
scores = [90, 85, 70]
for score in scores:
    print(score)

range(3) already gives 0, 1 and 2. The documentation’s formula for a range ends with r[i] < stop: the stop value itself is never included. Adding 1 to it is the mistake. Counting from 1 with range(1, len(scores) + 1) fails the same way, and it skips the first item too.

If you need the position as well as the item, use enumerate:

Passes: the position and the item togetherpython
for i, score in enumerate(scores):
    print(i, score)

2. The length used as the last position

Fails: len(scores) is 3, and the last position is 2python
scores = [90, 85, 70]
print(scores[len(scores)])
Passespython
print(scores[-1])

3. Looking at the next item

Comparing each item with the one after it runs off the end on the last step.

Fails on the last step: scores[i + 1] does not existpython
scores = [90, 85, 70]
for i in range(len(scores)):
    if scores[i] > scores[i + 1]:
        print("drop at", i)
Passes: stop one step earlypython
for i in range(len(scores) - 1):
    if scores[i] > scores[i + 1]:
        print("drop at", i)

4. The list is empty

An empty list has no position 0. Hidden tests often send an empty list, and your own tests probably never did.

Fails when there are no scorespython
scores = []
print(scores[0])
Passes: decide what an empty list should dopython
scores = []
if scores:
    print(scores[0])
else:
    print("no scores")

5. Deleting while looping

range(len(scores)) is worked out once, before the loop starts. When you delete an item, the list gets shorter and the range does not.

Fails: the list shrinks, the range does notpython
scores = [90, 40, 85, 30]
for i in range(len(scores)):
    if scores[i] < 50:
        del scores[i]
Passes: build a new list with the items you want to keeppython
scores = [90, 40, 85, 30]
scores = [s for s in scores if s >= 50]

6. Assigning to a position that doesn’t exist

You can’t create a position by assigning to it. The Python reference says “assignment to a subscripted sequence cannot add new items to a list”. The message is slightly different:

Fails with "IndexError: list assignment index out of range"python
squares = []
for i in range(3):
    squares[i] = i * i
Passes: append adds a new item at the endpython
squares = []
for i in range(3):
    squares.append(i * i)

7. The input is shorter than you expected

Your code expects three parts and the line has two. Or the line is blank. Or nobody passed a command line argument.

Fails: the line has only 2 partspython
line = "ada,90"
parts = line.split(",")
print(parts[2])
Passes: check before you indexpython
parts = line.split(",")
if len(parts) >= 3:
    print(parts[2])
else:
    print("line too short:", line)

Blank lines are the usual culprit in file input. When we split an empty string with no separator, we got an empty list, as the documentation says. So line.split()[0] fails on a blank line. Skip blank lines before you split them.

The same goes for sys.argv. The documentation says “argv[0] is the script name”. Your first real argument is sys.argv[1], and it only exists if someone passed one. When we ran a script with no arguments, len(sys.argv) was 1 and sys.argv[1] raised this error.

8. Rows of different lengths

Fails: the second row has only 2 itemspython
grid = [[1, 2, 3], [4, 5]]
for row in range(2):
    for col in range(3):
        print(grid[row][col])
Passes: each row decides how long it ispython
for row in grid:
    for value in row:
        print(value)

Messages that mean the same thing

Close relatives of this error, from our runs
MessageWhat caused it
IndexError: list assignment index out of rangeAssigning to a position that doesn’t exist (cause 6)
IndexError: pop from empty listCalling pop() on an empty list
IndexError: string index out of rangeThe same mistake on a string, such as "cat"[3]
IndexError: tuple index out of rangeThe same mistake on a tuple

The fix is the same for all four: check the length first.

Find which cause is yours

Four steps, in order
  1. Read the last line of the tracebackIt names the error. The lines above it give the file and the line number.
  2. Print the index and the lengthOn the line before the failing one, add print(i, len(scores)). Use your own names.
  3. Compare the two numbersThe index must be less than the length. If the length is 0, the list is empty: that is cause 4 or 7.
  4. Ask where the index came fromIf it comes from range, check the stop value. If it comes from input, check what the input really was.
Don’t hide it with try and except
Wrapping the line in try and except IndexError makes the message go away and leaves the bug in place. Your program then prints wrong answers quietly. Use try only when a missing item is a normal case you have planned for, such as an optional argument.

When it only fails on the grader

If your code passes your own tests and raises this error on the course’s grader, the grader sent an input you did not try. Empty input and a single item are the first two to test. Our guide to why code works locally but fails the autograder lists the inputs hidden tests usually use.

Still stuck?

Send us the file and the traceback. A senior engineer finds the cause, fixes it and explains why it broke, so you can explain it too. On our debug my code page, a single bug or error message is typically $45–$70, usually the same day.

Free price checkFind out what a fix would costUpload your code and the error message. You see a price range in under a minute, with no email needed. Your fixed price never goes above the top of that range.
Check your course rules first
Rules on outside help differ between schools, courses and assignments. Read your syllabus and honor code before you use any help, ours included. Our academic integrity page says what we do and what we won’t.

Related: Python homework help, data structures homework help and programming assignment help. For what this kind of help usually costs, see our price guide.

Questions about this error

What does list index out of range mean in Python?

It means the number you put in the square brackets is not a position in the list. Positions start at 0, so a list with 3 items has positions 0, 1 and 2. Asking for position 3, or for any position in an empty list, raises this error.

Why do I get list index out of range when my list is not empty?

Most often the index is one too high. The last position is the length minus 1, so a loop that runs up to the length itself fails on its final step. Print the index and the length just before the failing line and compare them.

How do I get the last item of a list without an error?

Use index minus 1, which always means the last item. It still fails on an empty list, so check that the list has items first if it might be empty.

Why does slicing not raise an IndexError?

Slices are forgiving by design. A slice that reaches past the end returns only the items that exist, and a slice that starts past the end returns an empty list. Only asking for a single position raises the error.

Should I use try and except to fix an IndexError?

Usually not. It hides the message without fixing the cause, and the program carries on with wrong data. Fix the index. Use try and except only when a missing item is a normal case that you handle on purpose.

What is the difference between IndexError and KeyError?

IndexError is for positions in lists, strings and tuples. KeyError is for dictionaries, when the key you asked for is not there. Both mean you asked for something the collection does not have.

Sources

Stuck on your own assignment?

Upload the prompt and see a predicted budget in under a minute. A senior engineer confirms the final price.

Keep reading

Related guides