Skip to content
DeepForgeby svx
All problems
EasyLinear Algebrala-016

Identity Matrix

Problem

Build the n x n identity matrix I, where I[i][j] = 1 if i == j and 0 otherwise.

If n is 0, return an empty list.

Hint

Nested comprehension with a conditional expression.

Test cases

case 1
in: [1]
expected: [[1]]
case 2
in: [2]
expected: [[1,0],[0,1]]
case 3
in: [3]
expected: [[1,0,0],[0,1,0],[0,0,1]]
case 4
in: [0]
expected: []
Starter codePython
def identity_matrix(n):
    # Your code here
    pass

4 test cases · run your code against them in the editor