Error while creating Identity matrix using list in python

Viewed 102

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]]
6 Answers

The problem with your code is that identity doesn't have 3 different null lists, it has 3 of the exact same null list. That's why in each iteration, you change value of all of them.

For example, you'll find that instead of the last for loop, if you simply run the following code:

identity[1][1]=1
print(identity)

you'll find that the outcome is

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

If you want to create an identity matrix with list, you can do the following: in each ith iteration, you append a row where the ith element is 1:

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

As a function:

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

eye(3)

Output:

[[1, 0, 0], [0, 1, 0], [0, 0, 1]]
identity = [[int(j == i) for j in range(n_rows)] for i in range(n_rows)]

Late to the party, but..

The point is that when you run the second loop (for j in range(3):) you are appending three times the object called null.

When you run the third loop for k in range(3): you are accessing and modifying the same object each time.

You can check what I mean printing the object id:

for k in range(3):
    print(id(identity[k]))

The solution is just to append a copy of the object, changing the second loop into:

for j in range(3):
    identity.append(null.copy()) # <-- added .copy()

You can use Numpy Library to create easily

import numpy as np 
data = np.eye(rows, columns) 
[![# Let's do that: 
data = np.eye(5,5) 
print(data)][1]][1]

Hope you understood! [1]: https://i.stack.imgur.com/wmKpe.png

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

a = int(input('enter the Number of matrix you need:: '))

lis = []


for i in range(a):
    new = [0]*a
    new[i] = 1
    lis.append(new)

# Now you can add many identity matrix, Enjoy!
Related