Skip to content

Lesson 1 of 9 · 24m

Numpy Arrays Are Not Fancy Python Lists

Understand dtype, shape, broadcasting, views, and copies so numerical code stays fast, correct, and predictable.

The first numpy bug I see from experienced Python engineers is usually not a math error. It is a type error disguised as math: object arrays, accidental copies, integer truncation, shapes that broadcast into nonsense. Python lists store pointers to objects. Numpy arrays are dense, typed blocks of memory. That difference is the entire reason the ecosystem exists.

dtype is part of the meaning

An array has one dtype. Every element must fit it:

import numpy as np

x = np.array([1, 2, 3], dtype=np.int64)
y = np.array([1.5, 2.5], dtype=np.float64)
z = np.array(["a", "bb"])

print(x.dtype, y.dtype, z.dtype)  # int64 float64 <U2

When dtypes mix, numpy promotes them according to rules you did not write. Integers can become floats, floats can truncate back into integers when assigned into integer arrays, and strings become fixed-width Unicode. In machine learning, dtype mistakes often appear as silent precision loss, category corruption, or memory blowups.

Shape is the API contract

Most model failures in production pipelines begin with a shape mismatch that a notebook hid by lucky broadcasting. Print shapes until shape checking becomes instinctive:

X = np.zeros((1000, 12))  # 1000 rows, 12 features
w = np.zeros((12,))
pred = X @ w
print(pred.shape)         # (1000,)

Keep the convention straight: rows are examples, columns are features. A single row should be shape (1, n_features), not (n_features,), when passed to scikit-learn.

Broadcasting is powerful and dangerous

Broadcasting expands smaller arrays along compatible dimensions:

X = np.array([[1.0, 2.0], [3.0, 4.0]])
center = np.array([0.5, 1.0])
print(X - center)

This subtracts [0.5, 1.0] from every row. But (1000, 12) and (1000,) do not mean what most newcomers expect; the vector is treated as a row shape (1, 1000) in some operations, or rejected in others. If you intend per-row scaling, reshape explicitly with (-1, 1).

Views share memory

Slicing often returns a view, not a copy:

a = np.arange(10)
b = a[::2]
b[:] = -1
print(a)  # [-1  1 -1  3 -1  5 -1  7 -1  9]

That is excellent for memory and terrible if you expected isolation. Use .copy() when ownership matters. In feature pipelines, accidental mutation through views can corrupt training data after you thought preprocessing was finished.

Vectorization is a memory-access strategy

Numpy is fast because loops move into optimized C over contiguous memory. This version is not merely shorter; it avoids Python object dispatch for every row:

total = np.sum((X - X.mean(axis=0)) ** 2, axis=1)

Still measure. Vectorized code can allocate enormous temporaries if written carelessly. Fast and memory-efficient are related, not identical.

Field notes

  • np.array on a ragged list now raises or creates object arrays depending on inputs; neither is a matrix.
  • float32 halves memory and often suffices for ML features, but accumulation error grows faster.
  • Always inspect X.dtype, X.shape, and X.flags['C_CONTIGUOUS'] before blaming the model.
  • NaN is a float concept; integer arrays cannot represent it without conversion or masked arrays.
  • Do not mutate arrays returned by another layer unless the ownership contract says you may.

Was this lesson helpful?

Sign in to rate