Topics in this subject
NumPy 1 min read Updated 4 Aug 2026

6. Reshaping

a = np.arange(12)

Function What it does View or Copy
reshape(shape) change shape, same data view when possible
resize(shape) in-place resize (can change size) modifies in place
ravel() flatten to 1-D view when possible
flatten() flatten to 1-D always copy
transpose() / .T permute axes view
swapaxes(a, b) swap two axes view
expand_dims(a, axis) insert new axis view
squeeze() drop size-1 axes view
a = np.arange(12)
a.reshape(3, 4)          # 3x4
a.reshape(3, -1)         # -1 = "infer this dimension" -> 3x4
a.reshape(2, 2, 3)       # 3-D

m = np.arange(6).reshape(2, 3)
m.T                      # 3x2 transpose
m.ravel()                # [0 1 2 3 4 5]
np.expand_dims(np.array([1,2,3]), axis=0)   # shape (1,3)
np.squeeze(np.zeros((1,3,1)))               # shape (3,)

💡 Tip: -1 lets NumPy compute one dimension automatically: a.reshape(-1, 1) makes a column vector.

⚠️ Common Mistake: reshape requires the total size to match (3*4 == 12). resize can grow/shrink and pad with zeros.

Interview Question: flatten vs ravel? ravel returns a view when possible (faster, memory-shared); flatten always returns a copy (safe to mutate).