Interview prep

24 NumPy interview questions, with answers.

NumPy interview questions on arrays, dtypes, views and copies, broadcasting, vectorisation and linear algebra: the foundations every data science library is built on.

NumPy questions test whether you think in arrays. Interviewers ask about broadcasting, views versus copies and vectorisation because the same ideas run through pandas, scikit-learn and PyTorch, and because getting them wrong causes silent bugs.

If an answer involves shapes, say the shapes out loud. That habit alone impresses interviewers.

These 24 questions are free. SchoolWhool's Foundations of AI course places 650+ interview questions right after the lessons they test, with a mock interview with Gaurav. See also the machine learning interview questions.

Arrays and dtypes

Why is NumPy faster than Python lists?
An array stores elements of one dtype in a contiguous block of memory, and operations run in compiled loops instead of the Python interpreter handling each element. A list stores pointers to separate Python objects, each with its own type information. Vectorised NumPy code is often 10 to 100 times faster than the equivalent loop.
What is a dtype, and why does it matter?
The dtype is the element type: int64, float32, bool and so on. It sets memory use, speed and precision; float32 halves memory compared with float64 but keeps fewer significant digits. Integer arrays can overflow silently, and mixed inputs are upcast, so np.array([1, 2.5]) is float64.
What are shape, ndim and size?
shape is the tuple of lengths along each dimension, ndim the number of dimensions and size the total number of elements. An array of shape (3,) is one-dimensional and behaves differently from a (3, 1) column or a (1, 3) row. Confusing them is the most common source of broadcasting bugs.
What are the main ways to create arrays?
np.array from a list; np.zeros, np.ones and np.full; np.arange for a step size and np.linspace for a number of evenly spaced points (prefer it for floats); np.eye for an identity matrix. np.empty doesn't initialise memory, so its values are garbage until you fill them.
What's the difference between reshape, ravel and flatten?
reshape returns the same data with a new shape, as a view when possible; -1 lets NumPy infer one dimension. ravel returns a flattened view when it can, while flatten always returns a copy. Reshaping never changes the number of elements.

Indexing, views and copies

When does indexing return a view, and when a copy?
Basic slicing (a[1:5], a[:, 0]) returns a view that shares memory, so changing it changes the original. Fancy indexing with integer arrays and boolean masks returns a copy. Call .copy() when you need independent data; np.shares_memory tells you if two arrays overlap.
How does boolean indexing work?
a[a > 0] keeps the elements where the mask is True and returns a one-dimensional copy. Combine conditions with &, | and ~, with parentheses: a[(a > 0) & (a < 5)]. Using and or or raises the error that the truth value of an array is ambiguous.
What is fancy indexing, and what's the gotcha with repeated indices?
Indexing with integer arrays, such as a[[0, 2, 4]], or a[rows, cols] to pick element pairs; np.ix_ selects a whole sub-grid. With repeated indices, a[[0, 0]] += 1 only adds 1 once, because the assignment is buffered. Use np.add.at(a, [0, 0], 1) to accumulate.
What does np.where do?
np.where(cond, x, y) picks from x where the condition holds and from y elsewhere, element by element. With only a condition, it returns the indices where it's True, like np.nonzero. For more than two outcomes, use np.select.
What does the axis argument mean?
It's the dimension you operate along, and for reductions it's the one that disappears: a.sum(axis=0) on a (rows, cols) array gives one sum per column. keepdims=True keeps that dimension with length 1, so the result broadcasts back against the original, for example when normalising each row.

Broadcasting and vectorisation

Explain the broadcasting rules.
NumPy compares shapes from the last dimension backwards. Two dimensions are compatible if they're equal or one of them is 1, and missing leading dimensions count as 1. Size-1 dimensions are stretched without copying. So (3, 4) + (4,) works, but (3, 4) + (3,) fails; you need shape (3, 1).
How would you standardise each column of a matrix?
(X - X.mean(axis=0)) / X.std(axis=0): the (n_features,) means broadcast across rows. For rows instead, use X.mean(axis=1, keepdims=True). Guard against columns with zero standard deviation, which produce inf or nan.
What is vectorisation, and does np.vectorize make code faster?
Vectorisation means expressing an operation on whole arrays so the loop runs in compiled code. np.vectorize is only a convenience wrapper: it still calls your Python function once per element, so it isn't meaningfully faster. Rewrite with array operations, ufuncs or broadcasting instead.
How do you compute pairwise distances without loops?
Broadcast a new axis: np.sqrt(((A[:, None, :] - B[None, :, :]) ** 2).sum(axis=-1)) gives an (n, m) matrix. That builds an (n, m, d) intermediate, so for large inputs use the identity |a|² + |b|² - 2a·b or scipy.spatial.distance.cdist. Saying the memory cost unprompted is a strong signal.
What are ufuncs?
Universal functions such as np.add, np.exp and np.maximum operate element by element with broadcasting, in compiled code. They accept out= and where= arguments and have methods like reduce, accumulate and outer. Python operators on arrays call ufuncs under the hood.

Linear algebra and numerics

What's the difference between *, @ and np.dot?
* multiplies element by element. @ (np.matmul) is matrix multiplication, (m, k) @ (k, n) giving (m, n), and it broadcasts over leading batch dimensions. np.dot agrees with @ for 2-D arrays but behaves differently for higher dimensions, so prefer @.
How do you solve a linear system, and why not invert the matrix?
Use np.linalg.solve(A, b). It's faster and more numerically stable than np.linalg.inv(A) @ b, which does extra work and amplifies rounding errors. For an overdetermined system, as in least-squares regression, use np.linalg.lstsq.
Why is 0.1 + 0.2 == 0.3 False, and how should you compare floats?
Binary floating point can't represent 0.1 exactly, so tiny rounding errors appear. Compare with a tolerance using np.isclose or np.allclose, setting rtol and atol sensibly. Also remember nan != nan; test with np.isnan.
How does NumPy handle missing values?
It uses np.nan, which only exists for floats, so an integer array with a missing value must become float. NaN propagates through sum and mean; the nan-aware versions (np.nanmean, np.nansum) skip it. Division by zero produces inf with a runtime warning rather than an error.
How do you make random numbers reproducible?
Create a generator with a seed, rng = np.random.default_rng(42), and draw from it: rng.normal(size=100). Pass the generator to functions that need randomness. The old global np.random.seed is legacy and shared across all code, which makes results fragile.

Practical NumPy

np.concatenate, np.stack, vstack or hstack?
concatenate joins arrays along an existing axis; stack creates a new axis, so all inputs must have the same shape; vstack and hstack are shorthands. Concatenating repeatedly inside a loop is quadratic, so collect pieces in a list and concatenate once, or preallocate.
How do you find the top k values efficiently?
np.argpartition(a, -k)[-k:] finds the indices of the k largest values in linear time without fully sorting; sort just those k if you need them in order. np.argsort sorts everything in O(n log n). np.argmax returns the first index of the maximum.
Why do memory layout and strides matter?
Strides are the bytes to step along each dimension. In C order, rows are contiguous, so operating along the last axis is cache-friendly and faster. A transpose is just a view with swapped strides, which is why some functions need np.ascontiguousarray first.
When would you use NumPy rather than pandas?
NumPy is for homogeneous n-dimensional numerical arrays and fast maths, and it's what models consume. pandas adds labelled rows and columns, mixed column types, missing-data handling, grouping and file I/O, and is built on NumPy. Use df.to_numpy() when you need the raw array.

First Principles, the SchoolWhool newsletter

One machine learning idea, explained properly, every week.

The intuition, the common mistake, and a five-minute way to try it yourself. Written by Gaurav.

Learn it properly, then the interview is the easy part.

Foundations of AI teaches NumPy and the rest of machine learning from first principles, with notebooks that check your work.