Linear Algebra Basics
Transpose
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.Tis a view: it shares memory witharr. Modifyingarr.Tmodifiesarr. To get an independent copy usearr.T.copy().- Transposing swaps axes: a
(rows, cols)array becomes(cols, rows). For higher-dimensional arraysarr.Treverses all axes; usenp.transpose(arr, axes)to specify a custom axis permutation. - Transposing is common before a matrix multiply: if A is
(m, n)and you wantA.T @ Ayou 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.