0

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

  • See [Python List copy](https://www.programiz.com/python-programming/methods/list/copy) – lurker Nov 03 '19 at 20:01
  • Possible duplicate of [How to clone or copy a list?](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list) – Mykola Zotko Nov 03 '19 at 20:22

1 Answers1

1

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.

akc
  • 89
  • 3