Home > Backend Development > Python Tutorial > How to Transpose a Matrix in Python?

How to Transpose a Matrix in Python?

Linda Hamilton
Release: 2024-10-19 09:03:02
Original
643 people have browsed it

How to Transpose a Matrix in Python?

Transpose a Matrix in Python

Transpose of a matrix is a fundamental operation in linear algebra, where the rows and columns of a matrix are swapped. In Python, this operation can be done efficiently using the zip function, which combines elements from multiple iterables into tuples.

To transpose a matrix, we need to iterate through each row of the matrix and create a new row by extracting elements from corresponding columns of the original matrix. We can use the * operator with zip to achieve this.

<code class="python">original_matrix = [[1, 2, 3], [4, 5, 6]]
transposed_matrix = zip(*original_matrix)

print(list(transposed_matrix))  # [(1, 4), (2, 5), (3, 6)]</code>
Copy after login

This operation creates a list of tuples, where each tuple represents a row in the transposed matrix. To obtain a list of lists, we can use a list comprehension or the map function:

<code class="python">transposed_matrix_list = [list(x) for x in zip(*original_matrix)]

# or

transposed_matrix_list = map(list, zip(*original_matrix))

print(transposed_matrix_list)  # [[1, 4], [2, 5], [3, 6]]</code>
Copy after login

The resulting transposed matrix has its rows and columns swapped, as desired.

The above is the detailed content of How to Transpose a Matrix in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template