Initialize matrix

78 views Asked by At

Why does the top line of code create a zeroed out matrix but the bottom four lines of code give an error ("list assignment index out of range")?

matrix = [ [ 0 for i in range (6)] for j in range(6)]

matrix = [[]]
for i in range (6):
    for j in range (6):
        matrix[i][j] = 0
1

There are 1 answers

0
Srgrn On BEST ANSWER

becouse the first line is filling a matrix the second matrix definition is actually creating an array of size 1 with another array as the 0 element the moment i=1 it fails

the correct form of the second part should be

matrix = []
for i in range(6):
    temp = []
    for j in range(6):
        temp.append(0)
    matrix.append(temp)