PYTHON
Perform Matrix Transposition Using Nested Lists
Learn to transpose a 2D list (matrix) in Python efficiently using nested list comprehensions. This snippet demonstrates a common operation in data processing and linear algebra.
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
transposed_matrix = [[row[i] for row in matrix] for i in range(len(matrix[0]))]
print("Original Matrix:")
for row in matrix:
print(row)
print("
Transposed Matrix:")
for row in transposed_matrix:
print(row)
How it works: This snippet demonstrates how to transpose a matrix (represented as a list of lists) using nested list comprehensions. The outer comprehension iterates through the columns of the original matrix (determined by `range(len(matrix[0]))`), and the inner comprehension iterates through each `row` to pick the element at the current column index `i`. This effectively swaps rows and columns, creating the transposed matrix in a concise and Pythonic way.