Arrays
14 min
NumPy's ndarray is the foundation almost every data/ML/quant library in
Python is built on (pandas, scikit-learn, PyTorch all use it under the
hood). Unlike a Python list, an array stores elements of one fixed type
contiguously in memory — that's what makes whole-array math fast.
import numpy as np
a = np.array([1, 2, 3, 4])
b = np.arange(4) # [0, 1, 2, 3] — like range(), but returns an array
c = np.zeros(3) # [0. 0. 0.]
d = np.linspace(0, 1, 5) # 5 evenly-spaced points from 0 to 1
shape and dtype are the two properties you'll check constantly when debugging array code — a wrong shape is the single most common NumPy bug.
Two-dimensional arrays (matrices) work the same way, just with a shape tuple of two numbers:
m = np.zeros((2, 3)) # 2 rows, 3 columns, all zeros
print(m.shape) # (2, 3)
Every element in an array shares one dtype — mixing an int and a float
in np.array([1, 2, 3.5]) silently upcasts the whole array to float64.
That's different from a Python list, which happily holds mixed types with
no conversion at all.
Write `make_range_array(n)`, returning a NumPy array containing 0, 1, ..., n-1 — use `np.arange`, not a Python loop.
Write `zeros_like_shape(rows, cols)`, returning a 2D NumPy array of zeros with shape `(rows, cols)` — use `np.zeros`.
What is the main practical difference between a NumPy array and a Python list?
You can create arrays with np.array/np.arange/np.zeros, and know that shape and dtype are the two properties to check first when something looks wrong.