# How to Transpose a Matrix in Python

Contents

In this article, you will learn how to transpose a matrix in Python.

## How to transpose a matrix

### Using the zip() function

In Python, you can transpose a matrix by using the built-in zip() function along with the * operator. Here’s an example:

```
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
transposed = zip(*matrix)
for row in transposed:
print(row)
```

This code will output the transposed matrix:

```
(1, 4, 7)
(2, 5, 8)
(3, 6, 9)
```

In the code above, *matrix is used to unpack the rows of the matrix and pass them as separate arguments to the zip() function. The zip() function then groups the corresponding elements of each row together, effectively transposing the matrix.

### Using nested list comprehension

You can transpose a matrix by using nested list comprehension. Here’s an example:

```
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
transposed = [[row[i] for row in matrix] for i in range(len(matrix[0]))]
for row in transposed:
print(row)
```

This code will output the same transposed matrix as before:

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

In the code above, a nested list comprehension is used to iterate over each column of the original matrix and create a new row in the transposed matrix. The outer list comprehension iterates over the indices of the columns, while the inner list comprehension iterates over the rows of the matrix and selects the element at the corresponding index.

### Using the NumPy library

You can transpose a matrix by using the NumPy library, which provides a transpose() function that can be used to transpose an array or matrix. Here’s an example:

```
import numpy as np
matrix = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])
transposed = np.transpose(matrix)
for row in transposed:
print(row)
```

This code will output the same transposed matrix as before:

```
[1 4 7]
[2 5 8]
[3 6 9]
```

In the code above, the original matrix is converted to a NumPy array using the np.array() function, and then the np.transpose() function is used to transpose the array. The resulting transposed matrix is also a NumPy array.