Python Multidimensional Matrix Definition indexing Error

1647 views python

n = 5
L = 6
Cache = [[-1 for x in range(n+1)] for y in range(L+1)]

The above code gives the below error.

Traceback (most recent call last):
File "/Users/globetrekker/Documents/CS5050/Assignment3/", line11, in <module>
IndexError: list index out of range

I am new to Python. So I don't understand how to rectify this error as I don't understand why can't I index into Cache[5][6]

answered question

2 Answers


Arrays are zero-indexed so, may be you can try following to access the last element i.e. fifth row and sixth element:


posted this

print(Cache[5]) #[-1, -1, -1, -1, -1, -1]

Each sublist has 6 elements, but lists are indexed from 0

To get the 6th element, use Cache[5][5]

posted this

Have an answer?


Please login first before posting an answer.