How to Transpose a Matrix in Python (List of Lists)

Swap rows and columns of a 2D list using nested loops to produce a transposed matrix.

Easy Python 3.6+ Aug 9, 2026 Lists & loops 13 views 0 copies

Python code

29 lines
Python 3.6+
def transpose(matrix):
    # Number of rows and columns in the original matrix
    rows = len(matrix)
    cols = len(matrix[0]) if rows > 0 else 0
    
    # Create a new matrix with dimensions swapped
    result = []
    for j in range(cols):
        new_row = []
        for i in range(rows):
            new_row.append(matrix[i][j])
        result.append(new_row)
    return result


if __name__ == "__main__":
    # Example 3x2 matrix
    original = [
        [1, 2, 3],
        [4, 5, 6]
    ]
    
    transposed = transpose(original)
    print("Original matrix:")
    for row in original:
        print(row)
    print("\nTransposed matrix:")
    for row in transposed:
        print(row)

Output

stdout
Original matrix:
[1, 2, 3]
[4, 5, 6]

Transposed matrix:
[1, 4]
[2, 5]
[3, 6]

How it works

The function determines the number of rows and columns from the input matrix. It then creates a result list with one row for each column of the original. Each new row is built by collecting the element at the same column index across all original rows, effectively swapping indices. This approach works for any rectangular matrix and leaves the original untouched. The outer loop iterates over columns, and the inner loop over rows, giving the transposed shape.

Common mistakes

  • Forgetting to check for an empty matrix, leading to IndexError
  • Assuming the matrix is square; the code handles rectangular matrices correctly
  • Modifying the original matrix while transposing
  • Using list comprehension incorrectly, which may be less readable for beginners

Variations

  1. Use `list(zip(*matrix))` to transpose with the zip function
  2. Use a list comprehension: `[[row[j] for row in matrix] for j in range(len(matrix[0]))]`

Real-world use cases

  • Preparing data for machine learning by converting feature rows to columns.
  • Reformatting spreadsheet data where rows and columns need to be swapped for analysis.
  • Rotating a grid-based game board by transposing its 2D array representation.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.