Complete worked example
python
import numpy as np
def inspect_example(values, rows, columns):
if type(rows) is not int or type(columns) is not int or rows < 1 or columns < 1:
raise ValueError("expected positive dimensions")
data = np.asarray(values, dtype=np.int64)
if data.ndim != 1 or data.size != rows * columns:
raise ValueError("element count does not match shape")
matrix = data.reshape(rows, columns)
return matrix.T.copy()- Reasoning
- The worked function validates positive whole-number dimensions, checks the flat vector length against rows times columns, reshapes in ordinary C order and transposes the result. It returns a copy so its output has a straightforward independent lifetime. A rectangular example is essential: many square or repeated-value examples hide the difference between reshape and transpose. Reshape may produce a view when strides permit and may need a copy otherwise. Current NumPy can explicitly reject a requested no-copy reshape when that layout is impossible. Do not teach reshape as either always allocating or always sharing; the array layout and requested order matter.