Python Multidimensional Matrix Definition indexing Error

1647 views python
-1

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

The above code gives the below error.

Traceback (most recent call last):
File "/Users/globetrekker/Documents/CS5050/Assignment3/temp.py", line11, in <module>
print(Cache[5][6])
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

7

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

print(Cache[4][5])

posted this
12

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?

JD

Please login first before posting an answer.