Your algorithm is correct, the problem lies in the way you create your empty matrix at the beginning, with
vertical_to_horizontal = [[0]*n]*n
The inner [0]*n
creates a list [0, 0]
Then, the outer *
operator creates a list that references twice this inner list - the very same object.
n = 2
v_to_h = [[0]*n] * n
print(id(v_to_h[0]), id(v_to_h[1]))
#140243497120456 140243497120456
The two [0, 0] lists in your matrix are in fact the same object, as their identical ids shows. So, when we do
v_to_h[0][0] = 5
we update the 0th element of v_to_h[0], but v_to_h[0] and v_to_h[1] are the same object, so we get twice the same list in the matrix:
print(v_to_h)
#[[5, 0], [5, 0]]
If you want to prevent that, you have to create different inner lists, so don't use the *
operator.
You can use a list comprehension, as in:
n = 2
v_to_h = [[0]*n for i in range(n)]
print(id(v_to_h[0]), id(v_to_h[1]))
#140243437130184 140243512804488
Here, our two lists are different objects.
So, your code could be:
def transpose_matrix(matrix):
n = len(matrix)
vertical_to_horizontal = [[0]*n for i in range(n)]
for i in range(n):
for j in range(n):
vertical_to_horizontal[i][j] = matrix[j][i]
return vertical_to_horizontal
print(transpose_matrix([[1,2],[3,4]]))
#[[1, 3], [2, 4]]
which does what you expect - though there are, of course, shorter and more efficient ways to transpose a matrix, as already indicated in the comments.