Search code examples
python-3.xlistfor-loopmatrixcomputer-science

Simple Identity matrix function


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)

Solution

  • 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]]