Search code examples
pythonlistmatrixlinear-algebramatrix-multiplication

Error while creating Identity matrix using list in python


I was trying to make an identity matrix to find the inverse. But I am stuck at this moment due to a bug in the code. A fresh eye would help a lot.

identity=[]
null=[]
for i in range(3):
    null.append(i*0)
for j in range(3):
    identity.append(null)
for k in range(3):
    identity[k][k]=1

print(identity)

The result I got

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

what I desired for

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

Solution

  • Expanding on @enke Answer, you can do it in modular form, creating an identity matrix of as many rows as you want.

    def eye(num):
        mat = []
        for i in range(num+1):
            row = [0]*(num+1)
            row[i]=1
            mat.append(row)
        return mat
    

    Now you can easily do

    eye(5)
    
    Out[2]: 
    [[1, 0, 0, 0, 0, 0],
     [0, 1, 0, 0, 0, 0],
     [0, 0, 1, 0, 0, 0],
     [0, 0, 0, 1, 0, 0],
     [0, 0, 0, 0, 1, 0],
     [0, 0, 0, 0, 0, 1]]