0

Expected Output:

indenitiy_matrix(3)
[[1, 0, 0], [0, 1, 0], [0, 0, 1]]

Actual Output with Error:

indenitiy_matrix(3)
[[1, 1, 1], [1, 1, 1], [1, 1, 1]] 
def identity_matrix(n):
    list_template = [[]]
    list_n = list_template*n

    for sub_l in list_n:
        sub_l.append(0)


    for val in range(n):
        # I have the feeling that the problem lies somewhere around here.
        list_n[val][val]=1


    return(list_n)
mujjiga
  • 16,186
  • 2
  • 33
  • 51
  • Your issue is caused by the problem explained in this question: https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly – saint-jaeger Nov 17 '20 at 21:34

2 Answers2

0

list_template*n does not create n copies, instead but all those n copies reference to only one copy. For example see this

a = [[0,0,0]]*2
# Now, lets change first element of the first sublist in `a`. 
a[0][0] = 1
print (a)
# but since both the 2 sublists refer to same, both of them will be changed. 

Output:

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

Fix for your code

def identity_matrix(n):
    list_n = [[0]*n for i in range(n)]
    for val in range(n):        
        list_n[val][val]=1
    
    return list_n

print (identity_matrix(5))

Output:

[[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]]
mujjiga
  • 16,186
  • 2
  • 33
  • 51
  • Thank you so much for your simple yet complete answer to my question. I am an engineering student learning python and I had never tried this website before. It makes me tremendously happy to know that some complete stranger helped me out of pure kindness. I am very very grateful. Thanks again. – Camilo Saravia Nov 17 '20 at 21:51
0

No, the problem lies here:

list_template = [[]]
list_n = list_template*n

After this, try doing:

list_n[0].append(1)  # let's change the first element

The result:

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

is probably not what you expect.

Briefly, the problem is that after its construction, your list consists of multiple references to same list. A detailed explanation is at the link given by @saint-jaeger : List of lists changes reflected across sublists unexpectedly

Finally, the numpy library is your friend for creating identity matrices and other N-dimensional arrays.

Jussi Nurminen
  • 2,257
  • 1
  • 9
  • 16
  • I copy-paste, the comment I wrote for the answer above as I feel the same for your response. ::: Thank you so much for your simple yet complete answer to my question. I am an engineering student learning python and I had never tried this website before. It makes me tremendously happy to know that some complete stranger helped me out of pure kindness. I am very very grateful. Thanks again. – Camilo Saravia Nov 17 '20 at 21:53