I want to transpose a matrix, and I use two method to initialize a nested list as a new matrix.
The first method to initialize a nested list is
re = [[0 for j in range(len(A))] for i in range(len(A[0]))]
The second method is
re = [[0]*len(A)]*len(A[0])
The code to transpose a matrix is as follows.
class Solution:
def transpose(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
l = len(A[0])
# method 1
re = [[0 for j in range(len(A))] for i in range(len(A[0]))]
# # method 2
# re = [[0]*len(A)]*len(A[0])
for i in range(len(A)):
for j in range(l):
re[j][i] = A[i][j]
return re
def test(self):
print(self.transpose([[1,2,3],[4,5,6]]))
tran = Solution()
tran.test()
However, the result of transposing a matrix by using two methods are different.
Output:
# mehtod 1
[[1, 4], [2, 5], [3, 6]]
# method 2
[[3, 6], [3, 6], [3, 6]]
Anybody can tell me the difference of this two method to initialize a list?