Errors and debugging
Read tracebacks and common errors
Use the exception type, message, and line number to locate a problem.
Lesson 34 of 63
Reading: about 2 min
Lesson + practice: about 13 min
Difficulty: Beginner
On this page4 sections
A traceback shows the path to a runtime error. Read the final line for the exception type and message, then locate the file and line above it. A SyntaxError appears before the program runs; a runtime error occurs while it is running.
values = [10, 20]
print(values[2])Traceback (most recent call last):
File "index_error.py", line 2, in <module>
print(values[2])
IndexError: list index out of rangeSave this file as index_error.py. Do not name it traceback.py: that name hides Python’s own traceback module, and other scripts in the same folder that use logging or unittest would then fail.
Your terminal may show the full path to the file instead of just its name. Python 3.11 and newer also add ^ or ~ marker lines under the part of the line that failed, and recent versions colour the output. The last line, with the error type and message, is the same.
Why this fails: the list has indexes 0 and 1. Index 2 raises IndexError. Other common exceptions include NameError for an unknown name, TypeError for an invalid operation on types, and ValueError for a value a conversion cannot use.
Make one change at a time
Correct the index and rerun the program. Changing one cause at a time makes it easier to see whether you fixed the reported problem.
values = [10, 20]
print(values[1])20
Why this works
A traceback identifies the route Python took to the failing operation. For a small script, the final exception type and the reported source line are often enough to start. IndexError means an index is outside a sequence; it does not mean the list itself disappeared.
Practice
Run the broken example, identify IndexError and line 2, then fix it. Try a missing dictionary key and identify the KeyError before correcting it.
Where is the exception type usually shown in a traceback?
Reveal answer
On the final line, alongside the error message.
Try another case
For a two-item list, which indexes are valid when counting from the front?
Check your answer
Reveal answer
Indexes 0 and 1 are valid; index 2 raises IndexError.
Your progress
Reveal the check answer or reach the end to complete this lesson.