Out of Range ErrorΒΆ

If you try to access a value at an index that is either less than 0 or larger than the last index in the list, you will get an error index out of range. Try running the example below to see what that error looks like. Then fix the code to work and run it again.


Whatever the length of the collection (the number of items in the collection), the highest valid index is one less than the length. (Since the first item in the collection is index 0.)

You have probably figured out why the range in the for loop stops at one less than the last value. If you access the range based on the len of the collection, you get exactly the right thing. We want to be able to do something like this:

Programming Challenge: Complete the program below to print out each item in the list myList, one per line. The code is very similar to the code above for printing each character in a string.


Discuss topics in this section with classmates.

Show Comments
Next Section - Creating a Procedure with Parameters