AlmostGr
AlmostGr

Reputation: 99

Index out of range error received, but I can't find out why?

I was hoping somebody can help me with the following:

I have the following data in some lists in lists --> A

A = [[['Ghost Block'], ['Ghost Block'], [-7.0, -30000.0, 84935.99999999991, 1.0, 5.0, 0, 84935.99999999991, 1, 1, ['Ghost', 3, 'Ghost', 'Ghost', 'Ghost', 'Ghost', 2, 'Ghost']], [-5.0, -30000.0, 84935.99999999991, 1.0, 4.0, -30000.0, 114935.99999999991, 2, 1, ['Ghost', 3, 'Ghost', 'Ghost', 'Ghost', 'Ghost', 2, 'Ghost']], [-3.0, 33475.49999999997, 84935.99999999991, 1.0, 3.0, -60000.0, 144935.9999999999, 3, 1, ['Ghost', 3, 'Ghost', 'Ghost', 'Ghost', 'Ghost', 2, 'Ghost']], [-1.0, 80158.49999999997, 84935.99999999991, 1.0, 2.0, -26524.50000000003, 111460.49999999994, 4, 1, ['Ghost', 3, 'Ghost', 'Ghost', 'Ghost', 'Ghost', 2, 'Ghost']], [1.0, 31301.99999999997, 84935.99999999991, 1.0, 1.0, 53633.99999999994, 31301.99999999997, 5, 1, ['Ghost', 3, 'Ghost', 'Ghost', 'Ghost', 'Ghost', 2, 'Ghost']]]]
TempValue = 0
Ghost_Block = -60000
for i in range(0,len(A)):
    for item in range(0,len(A[i])):
        if A[i][item] == 'Ghost Block':
            continue
        else:
            if A[i][item][9][0] == 'Ghost': # Neighbor 1
                TempValue += (Ghost_Block*A[i][item][4]) 

I receive the following error message:

--> 9             if Value_Spec_Depth[i][item][9][0] == 'Ghost': # Neighbor 1
IndexError: list index out of range

According to me Value_Spec_Depth[i][item][9][0] is not out of range. I hope someone can explain to me why I am receiving this error. Thanks

Upvotes: 1

Views: 48

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121476

For item values 0 and 1, A[i][item] is ['Ghost Block'], not 'Ghost Block' (note the 1-value list), so your if test never passes and the else block is executed instead:

>>> A[0][0]
['Ghost Block']
>>> A[0][1]
['Ghost Block']

As a result, the else suite tries to access index 9 of a list with only one.

You'd avoid this by actually testing for the list:

if A[i][item] == ['Ghost Block']:

or test the first element of a list:

if A[i][item][0] == 'Ghost Block':

Note that you can just loop over the lists directly, you don't need to produce indices. You also don't need to use continue if you just test for the inverse:

for sublist in A:
    for element in sublist:
        if element[0] != 'Ghost Block' and element[9][0] == 'Ghost':
            TempValue += Ghost_Block * element[4]

Another improvement would be to use custom classes instead of lists; it is not clear at all from using indices what meaning each value has.

Upvotes: 1

Related Questions