How to transpose an array in Python

Learn how to transpose an array in Python. Discover different methods, tips, real-world applications, and how to debug common errors.

How to transpose an array in Python
Published on: 
Tue
Mar 17, 2026
Updated on: 
Fri
Mar 20, 2026
The Replit Team

The transpose of an array in Python swaps its rows and columns. This fundamental operation is essential for data manipulation, scientific computing, and to prepare datasets for machine learning models.

In this article, you'll explore several techniques to transpose arrays, from simple loops to powerful library functions like NumPy's transpose(). You will find practical tips, see real world applications, and get advice to debug common issues.

Using np.transpose() for basic array transposition

import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
transposed = np.transpose(arr)
print(transposed)--OUTPUT--[[1 4]
[2 5]
[3 6]]

The NumPy library’s np.transpose() function provides a direct and efficient way to flip an array's dimensions. It takes the original array, arr, and returns a new array where the rows and columns are swapped. This is a core operation in linear algebra, and NumPy optimizes it for performance, making it ideal for large datasets.

  • The first row [1, 2, 3] becomes the first column.
  • The second row [4, 5, 6] becomes the second column.

Common transposition methods

Beyond NumPy's dedicated function, you can also transpose arrays using convenient shortcuts like the .T attribute or Python's versatile list comprehensions and zip() function.

Using the .T attribute for quick transposition

import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
transposed = arr.T
print(transposed)--OUTPUT--[[1 4]
[2 5]
[3 6]]

The .T attribute is a convenient shortcut for the np.transpose() function, offering a more concise syntax. Since it's an attribute and not a method, you access it directly on the array without parentheses. This approach is often preferred for its readability in simple transposition tasks.

  • Keep in mind that .T returns a view of the original array's data, not a copy. Any changes made to the transposed array will also modify the original array.

Transposing a list of lists with list comprehension

matrix = [[1, 2, 3], [4, 5, 6]]
transposed = [[row[i] for row in matrix] for i in range(len(matrix[0]))]
print(transposed)--OUTPUT--[[1, 4], [2, 5], [3, 6]]

List comprehensions offer a concise, pure Python way to transpose a matrix without needing external libraries. This technique builds the new rows by iterating through the columns of the original list of lists.

  • The outer loop, for i in range(len(matrix[0])), iterates through the column indices of the original matrix.
  • For each column index, the inner loop, [row[i] for row in matrix], constructs a new row by gathering the elements from that column.

It's an elegant solution that showcases Python's expressive power for data manipulation, though it can be less intuitive than NumPy for beginners.

Using zip() to transpose efficiently

matrix = [[1, 2, 3], [4, 5, 6]]
transposed = list(map(list, zip(*matrix)))
print(transposed)--OUTPUT--[[1, 4], [2, 5], [3, 6]]

The zip() function offers a Pythonic and memory-efficient way to transpose. It works by pairing elements from multiple lists together. The key is the asterisk * operator, which unpacks the outer list so that each inner list is passed to zip() as a separate argument.

  • zip(*matrix) groups the first elements of each row into a tuple, then the second, and so on.
  • Finally, map(list, ...) converts these output tuples into lists to form the final transposed matrix.

Advanced transposition techniques

For more complex transpositions, especially with multidimensional arrays, NumPy provides specialized functions like np.swapaxes(), np.moveaxis(), and np.einsum() for greater control.

Using np.swapaxes() for specific dimensions

import numpy as np
arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
swapped = np.swapaxes(arr, 0, 2)
print(f"Original shape: {arr.shape}, New shape: {swapped.shape}")
print(swapped)--OUTPUT--Original shape: (2, 2, 2), New shape: (2, 2, 2)
[[[1 5]
 [3 7]]

[[2 6]
 [4 8]]]

The np.swapaxes() function gives you precise control over transposition by letting you switch any two specific axes in a multidimensional array. Unlike a simple transpose that reverses all dimensions, this function is for targeted swaps. In the example, np.swapaxes(arr, 0, 2) exchanges the first axis (axis 0) with the third (axis 2).

  • While the array's shape remains (2, 2, 2), its internal data structure is rearranged. The elements once organized by depth are now organized by columns, reorienting the array's contents.

Using np.moveaxis() for multidimensional arrays

import numpy as np
arr = np.arange(24).reshape(2, 3, 4)
transposed = np.moveaxis(arr, [0, 2], [2, 0])
print(f"Original shape: {arr.shape}, New shape: {transposed.shape}")--OUTPUT--Original shape: (2, 3, 4), New shape: (4, 3, 2)

The np.moveaxis() function gives you fine-grained control by moving axes to specific new positions. Unlike swapping, you can rearrange multiple dimensions at once. In this example, np.moveaxis(arr, [0, 2], [2, 0]) reorders the array's structure.

  • The source axis at index 0 is moved to the destination index 2.
  • The source axis at index 2 is moved to the destination index 0.

This changes the array's shape from (2, 3, 4) to (4, 3, 2), effectively reorienting the data for complex operations.

Using np.einsum() for custom transposition patterns

import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
transposed = np.einsum('ij->ji', arr)
print(transposed)--OUTPUT--[[1 4]
[2 5]
[3 6]]

The np.einsum() function, short for Einstein summation, provides a powerful and flexible way to perform array operations using a simple string notation. It's a highly versatile tool that can handle transpositions, dot products, and other complex linear algebra tasks with a single, expressive command.

  • The string 'ij->ji' is the key. It tells NumPy how to map the input dimensions to the output dimensions.
  • The part before the arrow, ij, describes the input array's axes—i for rows and j for columns.
  • The part after the arrow, ji, specifies the desired output, swapping the axes to create the transpose.

Move faster with Replit

Replit is an AI-powered development platform that transforms natural language into working applications. Describe what you want to build, and Replit Agent creates it—complete with databases, APIs, and deployment.

For the array transposition techniques we've explored, Replit Agent can turn them into production tools:

  • An image processing tool that rotates or flips images by transposing their underlying pixel matrices.
  • A data analysis dashboard that pivots datasets, swapping rows and columns to prepare data for different charting libraries.
  • A scientific calculator that implements linear algebra functions, where transposing with arr.T or np.einsum() is a fundamental step.

Turn your own ideas into reality. Describe your app to Replit Agent, and it will build, test, and deploy it for you.

Common errors and challenges

While transposing arrays is often straightforward, you might run into a few common pitfalls, especially with 1D arrays or irregular data structures.

Fixing 1D array transposition issues with reshape

A common point of confusion is trying to transpose a one-dimensional NumPy array. Since it only has one dimension, such as a shape of (3,), calling .T on it has no effect. To get the result you want, you must first convert it into a two-dimensional array using the reshape() method. For instance, you can reshape it into a row vector with shape (1, 3) or a column vector with shape (3, 1), after which transposition will work as expected.

Handling the .T view vs copy confusion

Because the .T attribute returns a view of the array's data, any modifications to the transposed array will also change the original array. This behavior can lead to subtle and hard-to-find bugs in your code. If your goal is to create an independent transposed array, you must explicitly make a copy using the .copy() method, like this: transposed = arr.T.copy().

Dealing with irregular matrices in transposition

When working with Python's native lists of lists, transposition can fail if the inner lists have different lengths, creating what's known as an irregular or jagged matrix. Functions like zip() and list comprehensions assume a uniform structure and will either raise an error or produce unexpected results. The best approach is to first standardize the data by padding the shorter rows with a placeholder value—such as 0 or None—to create a rectangular matrix before you attempt to transpose it.

Fixing 1D array transposition issues with reshape

It's a frequent source of confusion when you try to transpose a 1D NumPy array. Because it lacks a second dimension to pivot, the .T attribute has no effect—the array's shape and orientation remain unchanged. The code below demonstrates this pitfall.

import numpy as np
arr = np.array([1, 2, 3, 4])
transposed = arr.T  # This doesn't change anything for 1D arrays
print(f"Original: {arr.shape}, Transposed: {transposed.shape}")

The code's output would show that the shape remains (4,) because a 1D array lacks a second dimension to swap. The .T attribute has nothing to operate on. The next example shows how to fix this.

import numpy as np
arr = np.array([1, 2, 3, 4])
arr_2d = arr.reshape(-1, 1)  # Convert to column vector first
transposed = arr_2d.T
print(f"Original: {arr.shape}, Reshaped: {arr_2d.shape}, Transposed: {transposed.shape}")

The solution is to first give the array a second dimension using the reshape() method. This is a common step when preparing data for linear algebra or machine learning models where matrix dimensions must be exact.

  • Using reshape(-1, 1) converts the 1D array into a 2D column vector.
  • Now that it's a 2D array, the .T attribute works as expected, turning a (4, 1) array into a (1, 4) array.

Handling the .T view vs copy confusion

A critical detail of NumPy's .T attribute is that it returns a view of the original array, not a new copy. This means both arrays share the same underlying data, which can cause unexpected side effects when making modifications.

The code below demonstrates this behavior. Notice how changing an element in the transposed array also alters the original, a common source of bugs.

import numpy as np
original = np.array([[1, 2], [3, 4]])
transposed = original.T
transposed[0, 0] = 99  # This modifies the original array too!
print("Original array after modification:")
print(original)

The assignment transposed[0, 0] = 99 alters the original array because .T creates a view, not a copy. This shared data can cause unintended side effects. The next example demonstrates how to prevent this behavior.

import numpy as np
original = np.array([[1, 2], [3, 4]])
transposed = original.T.copy()  # Create a copy
transposed[0, 0] = 99  # Original remains unchanged
print("Original array after modification:")
print(original)

To prevent unintended changes to your original data, create an explicit copy of the transposed view. By calling .copy() after .T, you get a completely independent array, as shown in the example.

  • Now, when you modify the new array, the original remains untouched. This is crucial for writing predictable functions that shouldn't have side effects on their inputs.

Dealing with irregular matrices in transposition

When using pure Python, transposing a list of lists only works if every inner list has the same length. If you have an irregular matrix, where rows have different lengths, functions like zip() will truncate the output, leading to silent data loss.

The code below shows this in action. Notice how the operation doesn't raise an error but instead produces an incomplete result because the second row is shorter than the first, causing the last element of the longer row to be dropped.

irregular_matrix = [[1, 2, 3], [4, 5]]  # Different row lengths
try:
   transposed = list(map(list, zip(*irregular_matrix)))
   print(transposed)
except Exception as e:
   print(f"Error occurred: missing values in the shorter row")

The zip() function pairs elements until the shortest row is exhausted, silently dropping the value 3 from the longer row. This behavior leads to incomplete results and data loss. The code below shows how to prevent this.

irregular_matrix = [[1, 2, 3], [4, 5]]
# Pad shorter rows with None or any placeholder
max_len = max(len(row) for row in irregular_matrix)
padded = [row + [None] * (max_len - len(row)) for row in irregular_matrix]
transposed = list(map(list, zip(*padded)))
print(transposed)

The solution is to first make the matrix rectangular, ensuring every row has the same number of elements before you attempt the transposition.

  • First, the code finds the length of the longest row using max().
  • It then pads any shorter rows with a placeholder like None until they all match this length.

Once the matrix is uniform, zip() can correctly transpose it without losing data. It's a crucial step when cleaning inconsistent data sources.

Real-world applications

Transposing an array is more than a technical step—it’s a key operation for analyzing data and manipulating images in the real world.

Transposing data for CSV column analysis with np.transpose()

When working with data from sources like CSV files, where information is often organized by rows, np.transpose() allows you to pivot the array to easily perform calculations on columns.

import numpy as np

# Sample dataset: student scores (rows are students, columns are subjects)
student_data = np.array([[85, 90, 78], [92, 88, 95], [75, 82, 80]])
subject_data = np.transpose(student_data)

# Calculate average score for each subject
subject_averages = np.mean(subject_data, axis=1)
print(f"Average scores by subject: {subject_averages}")

This example shows how transposing simplifies data analysis. The initial student_data array is organized by student, with each row holding one student's scores. To analyze the data by subject instead, you use np.transpose() to flip the array's orientation.

  • After transposing, each row in the new subject_data array conveniently groups all scores for a single subject.
  • You can then calculate the average score for each subject by applying np.mean() along axis=1, which computes the mean for each row.

Image rotation using matrix transposition with .T

Since an image is just a matrix of pixel values, you can perform a 90-degree rotation by simply transposing it with the .T attribute.

import numpy as np
import matplotlib.pyplot as plt

# Create a simple 5x5 "image" (1s forming an L shape)
image = np.zeros((5, 5))
image[1:5, 1] = 1  # Vertical line
image[4, 1:4] = 1  # Horizontal line

# Rotate the image using transpose
rotated_image = image.T

# Display the results
print("Original image:")
print(image)
print("\nRotated image:")
print(rotated_image)

This example constructs a simple 5x5 "image" from a NumPy array. It begins with a canvas of zeros and then uses slicing to draw an "L" shape by setting specific elements to one. The key step is image.T, which swaps the array's rows and columns.

  • The vertical part of the "L" becomes horizontal.
  • The horizontal part becomes vertical.

This axis swap effectively reorients the "L" shape within the grid. It's a foundational technique for many image processing tasks.

Get started with Replit

Turn these concepts into a real tool with Replit Agent. Try prompts like, “a web app that rotates images by transposing their pixel matrix,” or “a data utility that pivots CSV files for analysis.”

Replit Agent writes the code, tests for errors, and handles deployment, turning your description into a fully functional application. Start building with Replit.

Get started free

Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.

Get started for free

Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.