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?
What is a dtype, and why does it matter?
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?
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?
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?
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.
(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?
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?
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?
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?
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?
np.isclose or np.allclose, setting rtol and atol sensibly. Also remember nan != nan; test with np.isnan.How does NumPy handle missing values?
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?
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?
np.ascontiguousarray first.When would you use NumPy rather than pandas?
df.to_numpy() when you need the raw array.Keep preparing
26 pandas interview questions
pandas interview questions on indexing, cleaning, groupby, merges, reshaping and performance, including the warnings and silent bugs interviewers love to ask about.
ArticleMatrix multiplication with shapes: map a batch of vectors
Trace a 2×3 batch through a 3×2 matrix, calculate individual entries and distinguish matrix multiplication from broadcasting and elementwise products.
ArticlePython for machine learning and AI: what to learn first, and what to skip
Learn core Python first, then NumPy, pandas, Matplotlib and scikit-learn, in that order. What each stage gives you, what to skip and when you know enough.
Interview prep28 scikit-learn interview questions
The scikit-learn questions interviewers actually ask: the estimator API, pipelines and leakage, cross-validation, tuning, and the practical traps that separate people who've used it from people who've read about it.
Interview prep28 Python interview questions
Python interview questions for data science, ML and backend roles: mutability, data structures, functions and scope, classes, generators, errors and the GIL, with the pitfalls interviewers probe.
ArticleLogistic regression from scratch: fit probabilities and inspect errors
Implement stable binary cross entropy and its gradient in NumPy, train on invented data and compare held-out predictions with a constant baseline.
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.