leandro minervino
leandro minervino

Reputation: 27

Matrix code not working even is similar to other

I was trying to create a code for a identity matrix and came out with this code:

def identidade(n):
i =0
l = [0] * n
l1 = [l.copy()] *n
for i in range (n):
    l1[i][i] = 1
    print(l1)
return l1

the output is:

 [[1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1],
 [1, 1, 1, 1, 1]]

But i came along with a very similar code in the internet:

def identity(n):
m=[[0 for x in range(n)] for y in range(n)]
for i in range(0,n):
    m[i][i] = 1
return m

that returns:

 [[1, 0, 0, 0, 0],
 [0, 1, 0, 0, 0],
 [0, 0, 1, 0, 0],
 [0, 0, 0, 1, 0],
 [0, 0, 0, 0, 1]]

So, my question is why my code doesn't return the correct output when selecting the element in the list of lists (l1[i][i] = 1) ? tks in advance

Upvotes: 0

Views: 40

Answers (1)

akc
akc

Reputation: 89

The actual problem here is that you are using the * operator to create (as you hope) the copies of the '[l.copy()]' list, but it actually creates references. Using the copy() inside of the square brackets just breaks the connection to the original 'l' list, but does not solve the problem with creation of references to the newly created copy.

Just try to replace the * operator with for loop - this will solve your problem.

Upvotes: 1

Related Questions