Jordan
Jordan

Reputation: 21

"List index out of range" error in Python

I am making a simple Checkers again. And, in order to keep track of all the locations for the checkers to move to, I created a list to add all of the locations.

Locations = [(10, 10), (70, 10), (130, 10), (190, 20), (250, 10), (310, 10), \
         (370, 10), (430, 10), (10, 70), (130, 70), (190, 70), (250, 70), \
         (310, 70), (370, 70), (430, 70), (10, 130), (70, 130), (130, 130), \
         (190, 130), (250, 130), (310, 130), (370, 130), (430, 130), \
         (10, 190), (70, 190), (130, 190), (190, 190), (250, 190), (310, 190), \
         (370, 190), (430, 190)]

However, when I try to execute the program, I always get: Ld8 = Locations[31] - list index out of range

So, I thought maybe a list can only contain certain amount of numbers. So, I created a second Locations list and added rows E - H, so to split up the list. But, I still receive the same error of index being out of range. (Ld8 is the variable storing the location for Row D, Column 8)

Upvotes: 2

Views: 3155

Answers (6)

john
john

Reputation: 25

Indexes of arrays for most programming languages start at 0 and not 1.

Upvotes: 0

龚元程
龚元程

Reputation: 417

Locations[31] tries to access the 32nd item in the list (which doesn't exist)

Upvotes: 0

Donald Miner
Donald Miner

Reputation: 39943

The largest index in that list is 30, not 31. Indexes in lists (in most languages) start with zero. So (10,10) is at index 0 and (430,190) is at index 30.

If you are trying to index at the end of the list in python, I suggest you index by Locations[-1].

If you are trying to use len, you need to subtract 1: Locations[len(Locations) - 1]

Upvotes: 2

GP89
GP89

Reputation: 6740

List indexes start from 0. So your list has 31 items you can access them with indexes 0-30. Locations[31] refers to the 32nd item which doesn't exist

Upvotes: 3

naeg
naeg

Reputation: 4002

You have a very basic understanding problem:

>>> Locations = [(10, 10), (70, 10), (130, 10), (190, 20), (250, 10), (310, 10), (370, 10), (430, 10), (10, 70), (130, 70), (190, 70), (250, 70), (310, 70), (370, 70), (430, 70), (10, 130), (70, 130), (130, 130), (190, 130), (250, 130), (310, 130), (370, 130), (430, 130), (10, 190), (70, 190), (130, 190), (190, 190), (250, 190), (310, 190), (370, 190), (430, 190)]
>>> len(Locations)
31
>>> Locations[0] # first element
(10, 10)
>>> Locations[30] # last element
(430, 190)
>>> Locations[31] # doesn't exist!
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

The elements in Locations go from 0 to 30, because there are 31 elements in total.

Upvotes: 6

Gandi
Gandi

Reputation: 3652

Emm... The list's elements are numbered from 0, not from 1. I have counted your list and I see elements from 0 to 30.

Sometimes I even forget it's possible to start counting at 1...

Upvotes: 1

Related Questions