The shape attribute is a tuple of axis lengths. reshape returns a new view (when possible) with different dimensions but the same total size.
Rules of reshape
- Total elements must match:
prod(old_shape) == prod(new_shape) -1infers one dimension:arr.reshape(2, -1)- Row-major (C) order: last index varies fastest
1D ↔ 2D
import numpy as np
a = np.arange(6)
b = a.reshape(2, 3)
print(a.shape, '→', b.shape)
print(b)
ravel and flatten
ravel()— 1D view when possibleflatten()— always returns a copy
Important interview questions and answers
- Q: reshape(3, 4) from size 12?
A: Valid—12 elements rearranged into 3 rows × 4 columns. - Q: When does reshape fail?
A: When requested shape product does not equal array size.
Self-check
- Reshape range(8) to (2, 4).
- What does -1 mean in reshape?
Tip: Use -1 in reshape to infer one dimension quickly.
Interview prep
- reshape rule?
Total elements must match; -1 infers one dimension.
- ravel vs flatten?
ravel view when possible; flatten always copies.