The code is almost correct except the line matrix.append(matrix[i][j])
. Let's dig a bit...
Consider the line
matrix = [[0]*A for i in range(A)]
Here a new matrix of the shape A x A
is created which is what's expected in the final answer.
Then we have the two for loops which are iterating through each row and each column.
for i in range(A): # Iterating through each rows
for j in range(A): # Iterating through each columns
...
Now, let's look at the erroneous line
matrix.append(matrix[i][j])
This line adds new values at the end of a perfectly fine matrix which distorts the final shape of the matrix.
What you instead need to do is assign values in the corresponding row and column. Effectively, something like this:
matrix[i][j] = ...
Now, on the right hand side of the above expression goes (i * A) + (j + 1)
. So you can rewrite your program as follows:
A = 3
# Initialize the matrix
matrix = [[0]*A for i in range(A)]
for i in range(A):
for j in range(A):
# Replace the value at the corresponding row and column
matrix[i][j] = (i * A) + (j + 1)
print(matrix)
Output:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
This is a pure Python solution, thus, it does not require any external library.