You're encountering an issue with your code when trying to create an identity matrix using the approach [[0]*n]*n. The problem arises because this method creates references to the same row, resulting in modifications affecting the entire column. To resolve this, you can use either a nested list comprehension or a loop to construct the identity matrix correctly. Here's an improved version of your code:
def identity(n):
matrix = [[0] * n for _ in range(n)] # Create an empty matrix
for i in range(n):
matrix[i][i] = 1 # Set diagonal elements to 1
return matrix
print(identity(5))
By utilizing this code, you'll obtain the desired identity matrix for n=5:
[[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]]