3

I wanted to do the transpose of a matrix. I don't want to use numpy. I am getting the following error, (below code). Any help is appreciated

    matrix = [[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3]]

    transposed = []

    for i in range(7):
        new=[]
        for row in matrix:
            new.append(row[i])
        transposed.append(lst)
    print(transposed)

error:

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-106-856d3ec27942> in <module>()
      6     new=[]
      7     for row in matrix:
----> 8         new.append(row[i])
      9     transposed.append(lst)
     10 print(transposed)

IndexError: list index out of range
Sai Ananth
  • 61
  • 1
  • 2
  • 5

3 Answers3

13

You can transpose a list of list with a cool one liner using zip, and *unpacking:

m = [[1, 1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2, 2, 2], [3, 3, 3, 3, 3, 3, 3]]
list(zip(*m))

output:

[(1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 2, 3)]
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
5

Simple loops way:

matrix = [[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3]]  

print([[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))])
# [[1, 1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2, 2, 2], [3, 3, 3, 3, 3, 3, 3]]

Or zip:

matrix = [[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3]]

print(list(map(list, zip(*matrix))))
# [[1, 1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2, 2, 2], [3, 3, 3, 3, 3, 3, 3]]
Austin
  • 25,759
  • 4
  • 25
  • 48
3

In your code 0<=i<7, but a row has length 3. @giser_yugang's ansewr is correct, and you can use zip, too:

transposed= list(zip(*matrix))

*: breaks the matrix into its elements, i.e. its rows; zip: group the row elements into columns as tuples;

print(transposed)
Out: [(1, 1, 1, 1, 1, 1, 1), (2, 2, 2, 2, 2, 2, 2), (3, 3, 3, 3, 3, 3, 3)]

Or you can convert tuples into list:

transposed=[ list(e) for e in zip(*matrix)]
print(transposed)
Out: [[1, 1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2, 2, 2], [3, 3, 3, 3, 3, 3, 3]]
kantal
  • 2,331
  • 2
  • 8
  • 15