def get_matrix(n): rows, columns = n,n matrix = [[0]*n]*n for i in range(n): matrix[i][i] = 1 return matrix
This was my code. I know that we can make a [0] list with n zeros by doing [0]*n.
I thought if I further multiply that, I would get a [0] n square matrix. Running the code always returned a matrix with all elements 1. I put the code to the visualizer and found that a single list of n zeros is created and every row of the matrix points to that same list which is why when I edit, it edits that list and every position becomes 1.
Is there any way to create the entire matrix in a single iteration without going through O(n2) complexity similar to what I was trying to attempt? I already know the double for loop approach