PYTHON

Transpose a Matrix (List of Lists)

Learn to efficiently transpose a 2D matrix, represented as a list of lists, in Python using list comprehensions and the `zip` function, transforming rows into columns.

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

# Using zip and list comprehension
transposed_matrix = [list(row) for row in zip(*matrix)]

print("Original Matrix:")
for row in matrix:
    print(row)

print("
Transposed Matrix:")
for row in transposed_matrix:
    print(row)
    
# Example with different dimensions (zip handles this gracefully)
matrix_rect = [
    [10, 11],
    [12, 13],
    [14, 15]
]
transposed_rect = [list(row) for row in zip(*matrix_rect)]
print("
Original Rectangular Matrix:")
for row in matrix_rect:
    print(row)
print("
Transposed Rectangular Matrix:")
for row in transposed_rect:
    print(row)
How it works: This snippet demonstrates transposing a matrix (represented as a list of lists) using Python's `zip` function combined with list comprehension. The `*matrix` unpacks the rows as separate arguments to `zip`. `zip` then aggregates elements from each row, effectively pairing `(matrix[0][0], matrix[1][0], matrix[2][0])`, `(matrix[0][1], matrix[1][1], matrix[2][1])`, and so on. Finally, `list(row)` converts each tuple generated by `zip` back into a list, forming the new rows of the transposed matrix.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs