Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (12.7k points)

I just need to create a function identity which return n identity matrix.

Example:

identity(3)

output's [[1,0,0][0,1,0][0,0,1]]

I also tried the below code:

def identity(n):

matrix=[[0]*n]*n

i=0

while i<n:

    matrix[i][i]=1

    i+=1

return matrix

Also tried with the range function, but it doesn't work.

def identity(n):

    matrix=[[0]*n]*n

    k=matrix[:]

    i=0

    for i in range(1,n):

        matrix[i][i]=1

        i+=1

    return k

print(identity(5))

For n=5, it outputs:

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

1 Answer

0 votes
by (26.4k points)

Try the below code:

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

Interested to learn python in detail? Come and Join the python course.

Related questions

Browse Categories

...