Swap rows and columns of a 2×3 matrix to produce a 3×2 result. A pre-allocated output matrix is filled cell by cell with out[j][i] = a[i][j]. The replay shows out filling column by column from the source rows, making the index swap visible before the one-attribute NumPy version.

By hand

With NumPy

arr.T returns the transpose as a view — no data is copied. The snapshot shows the original (2, 3) shape and the transposed (3, 2) shape.

naive.py
a = [[1, 2, 3], [4, 5, 6]]
rows = len(a)
cols = len(a[0])
out = [[0, 0], [0, 0], [0, 0]]
for i in range(rows):
    for j in range(cols):
        out[j][i] = a[i][j]
print('RESULT:', out)
library.py
import numpy as np

a = [[1, 2, 3], [4, 5, 6]]
arr = np.array(a)
result = arr.T
print('arr: shape:', arr.shape, 'dtype:', arr.dtype, 'values:', arr.tolist())
print('result: shape:', result.shape, 'dtype:', result.dtype, 'values:', result.tolist())
print('RESULT:', result.tolist())
arr: shape: (2, 3) dtype: int64 values: [[1, 2, 3], [4, 5, 6]]
result: shape: (3, 2) dtype: int64 values: [[1, 4], [2, 5], [3, 6]]
RESULT: [[1, 4], [2, 5], [3, 6]]

Implementation notes

  • arr.T is a view: it shares memory with arr. Modifying arr.T modifies arr. To get an independent copy use arr.T.copy().
  • Transposing swaps axes: a (rows, cols) array becomes (cols, rows). For higher-dimensional arrays arr.T reverses all axes; use np.transpose(arr, axes) to specify a custom axis permutation.
  • Transposing is common before a matrix multiply: if A is (m, n) and you want A.T @ A you get a (n, n) square matrix, useful in linear regression normal equations.
  • Shape, dtype, and values are shown explicitly here because ndarray.__repr__ output varies with NumPy version and print options.