0

I am trying to use nested list comprehension to transpose a matrix in python

I am confused as to why this won't return a transposed matrix. I am trying to implement a matrix transpose in python, specifically using nested list comprehension.

return [[row[i] for i in range(len(m))] for row in m]

m is my matrix above.

m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

I get back the same matrix I passed in for the return statement above. What am I doing wrong?

random_coder_101
  • 1,782
  • 3
  • 24
  • 50

1 Answers1

1

It is not clear why do you expect that your code can trapspose matrix. So I can't explain what is wrong here. You just copy the matrix instead of transposing. Try this:

m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print [[row[i] for row in m] for i in range(len(m[0]))]
Ilya
  • 4,583
  • 4
  • 26
  • 51