transpose matrix in python

To transpose a matrix in Python, you can use the zip() function in combination with the * operator:

main.py
def transpose(matrix):
    return list(zip(*matrix))
53 chars
3 lines

Here's an example usage:

main.py
matrix = [[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9]]

transposed_matrix = transpose(matrix)

print(transposed_matrix)
# Output: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
172 chars
9 lines

In this example, the zip(*matrix) expression transposes the matrix by unpacking the rows of the original matrix as arguments to zip(). The zip() function then creates tuples by pairing corresponding elements from each row. Finally, list() is used to convert the resulting zip object into a list.

Note that the resulting transposed matrix is a list of tuples. If you prefer to have a list of lists, you can modify the transpose() function as follows:

main.py
def transpose(matrix):
    return [list(row) for row in zip(*matrix)]
70 chars
3 lines

With this modification, the output will be:

main.py
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
34 chars
2 lines

By transposing a matrix, the rows become columns and the columns become rows.

related categories

gistlibby LogSnag