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.
Python code
29 linesdef 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
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
- Use `list(zip(*matrix))` to transpose with the zip function
- 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
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.