NumPy Interview Questions and Answers
Last updated 2026-11-19
NumPy is the base under pandas, scikit-learn and PyTorch tensors, and data science interviews check it through shape reasoning: what does this broadcast to, what does axis=0 do, does this change the original array. Most mistakes come from guessing a shape instead of working it out.
The answers below state the shapes explicitly and include code with verified results. Pair this page with pandas interview questions for tabular work and with Python interview questions for the language itself.
| Typical rounds | Python data task, ML coding, shape reasoning questions |
|---|---|
| Core skills | Broadcasting, indexing, axis, linear algebra, vectorisation |
| Questions here | 15 worked questions |
Shape reasoning in three rules
- Broadcasting aligns shapes from the right; each pair of dimensions must be equal or one of them must be 1.
- The axis argument names the dimension that disappears: sum over axis=0 of a (2, 3) array gives shape (3,).
- Basic slicing returns a view of the same memory; fancy indexing and boolean masks return copies.
Why interviews like numpy
Numpy questions are quick to ask and hard to bluff. A candidate who can predict the output shape of a broadcast, or write a vectorised pairwise distance without a loop, usually handles machine learning code well. Practise saying the shapes out loud before running the code.
NumPy Interview Questions and Answers: questions with worked answers
1 Why is a NumPy array faster than a Python list?
easyA NumPy array stores elements of one dtype in a contiguous block of memory, and operations run in compiled C loops, often using SIMD instructions. A list holds pointers to separate Python objects, and each operation goes through the interpreter with type checks. Adding two million-element arrays is typically tens to a hundred times faster than a list comprehension. The trade-off is that arrays have a fixed type and size, so appending repeatedly is slow.
2 Explain broadcasting. What is the result shape of (3, 1) + (1, 4), of (3,) + (2, 3), and of (3,) + (3, 2)?
mediumCompare shapes from the right; dimensions are compatible if equal or if one is 1, and the size 1 dimension is stretched. (3, 1) with (1, 4) gives (3, 4). (3,) is treated as (1, 3) and broadcasts with (2, 3) to (2, 3). (3,) against (3, 2) compares 3 with 2 on the last axis, which fails with a ValueError. Fix it with a[:, None] to make the first array (3, 1).
pythonimport numpy as np a = np.arange(3).reshape(3, 1) # (3, 1) b = np.arange(4).reshape(1, 4) # (1, 4) print((a + b).shape) # (3, 4) print((np.arange(3) + np.ones((2, 3))).shape) # (2, 3) print((np.arange(3)[:, None] + np.ones((3, 2))).shape) # (3, 2)3 What is the difference between a view and a copy?
mediumA view shares memory with the original, so changing one changes the other. Basic slicing, reshape when possible and transpose return views. Fancy indexing with a list or a boolean mask returns a copy. Use .copy() to detach explicitly and np.shares_memory to check. The classic bug is modifying a slice and unexpectedly changing the source array.
pythonx = np.arange(5) v = x[1:4]; v[0] = 99 print(x) # [ 0 99 2 3 4] view changed the original c = x[[1, 2]]; c[0] = -1 print(x) # unchanged: fancy indexing copies4 How does the axis argument work? Given a of shape (2, 3), what do a.sum(axis=0) and a.sum(axis=1) return?
easyThe named axis is collapsed. For a = [[1, 2, 3], [4, 5, 6]], axis=0 sums down the rows and returns [5, 7, 9] with shape (3,). axis=1 sums across columns and returns [6, 15] with shape (2,). Use keepdims=True to keep the reduced axis as size 1 so the result broadcasts back against the original, as in normalising each row by its sum.
pythona = np.array([[1, 2, 3], [4, 5, 6]]) print(a.sum(axis=0), a.sum(axis=1)) # [5 7 9] [ 6 15] row_norm = a / a.sum(axis=1, keepdims=True)5 Use boolean masks and np.where.
easyA boolean array of the same shape selects elements; combine conditions with & and | in parentheses, not and/or. np.where(cond, x, y) picks elementwise, and with a single argument it returns the indices where the condition is true. np.select handles several conditions.
pythonv = np.array([3, -1, 4, -5, 9]) print(v[(v > 0) & (v < 9)]) # [3 4] print(np.where(v > 0, v, 0)) # [3 0 4 0 9] print(np.where(v < 0)[0]) # [1 3]6 What is the difference between reshape, ravel and flatten, and what does -1 mean in reshape?
easyreshape changes the shape without changing data and returns a view when possible. ravel returns a flattened view when possible, and flatten always returns a copy. A -1 in reshape means that this dimension is inferred from the total size: an array of 12 elements reshaped to (3, -1) becomes (3, 4). Only one dimension can be -1, and the sizes must divide exactly.
7 Find the indices of the 3 largest values without sorting the whole array.
mediumnp.argpartition does a partial sort in O(n) and puts the k largest in the last k positions, but those positions are not themselves ordered, so sort just those k. A full argsort is O(n log n), fine for small arrays. For a (n, m) matrix, apply it along an axis.
pythonx = np.array([5, 1, 9, 3, 7, 8]) idx = np.argpartition(x, -3)[-3:] # indices of 9, 8, 7 in any order idx = idx[np.argsort(-x[idx])] print(idx, x[idx]) # [2 5 4] [9 8 7]8 Difference between the star operator and @ for arrays? What shapes does matrix multiplication need?
easyThe star operator is elementwise multiplication with broadcasting, while @ (or np.matmul) is matrix multiplication. For (m, k) @ (k, n) the inner dimensions must match and the result is (m, n). A (3,) vector @ a (3,) vector gives a scalar dot product. In batched cases, matmul broadcasts leading dimensions, so (b, m, k) @ (b, k, n) gives (b, m, n).
9 Standardise each column of a matrix to zero mean and unit variance.
easySubtract the column mean and divide by the column standard deviation, computed along axis=0. Broadcasting stretches the (d,) statistics over all rows. Guard against zero variance columns. Note np.std divides by n by default, whereas pandas std divides by n - 1; pass ddof=1 for the sample version.
pythonX = np.array([[1., 10.], [2., 20.], [3., 30.]]) mu, sd = X.mean(axis=0), X.std(axis=0) Z = (X - mu) / np.where(sd == 0, 1, sd) print(Z[:, 0]) # [-1.2247 0. 1.2247]10 Solve the system 2x + y = 5, x + 3y = 10 with NumPy.
easyWrite it as A v = b with A = [[2, 1], [1, 3]] and b = [5, 10], and call np.linalg.solve, which uses LU decomposition and is more accurate and faster than computing the inverse. The solution is x = 1 and y = 3, which checks: 2 + 3 = 5 and 1 + 9 = 10. If A is singular, solve raises LinAlgError; for overdetermined systems use np.linalg.lstsq.
pythonA = np.array([[2., 1.], [1., 3.]]); b = np.array([5., 10.]) print(np.linalg.solve(A, b)) # [1. 3.]11 Compute all pairwise Euclidean distances between two sets of points without loops.
hardUse broadcasting: insert axes so that A has shape (n, 1, d) and B has shape (1, m, d), subtract to get (n, m, d), square, sum over the last axis and take the square root. This creates an n x m x d temporary array, which can be large. A leaner formula uses |a - b|^2 = |a|^2 + |b|^2 - 2 a . b computed with one matrix product, but clip tiny negative values from rounding before the square root.
pythonA = np.array([[0., 0.], [3., 4.]]) B = np.array([[0., 0.], [6., 8.], [3., 0.]]) D = np.sqrt(((A[:, None, :] - B[None, :, :]) ** 2).sum(axis=-1)) print(D) # [[0. 10. 3.] [5. 5. 4.]] d2 = (A**2).sum(1)[:, None] + (B**2).sum(1)[None, :] - 2 * A @ B.T D2 = np.sqrt(np.clip(d2, 0, None))12 What integer overflow problems exist in NumPy, and how do you compare floats?
mediumFixed-width integers wrap silently in array arithmetic: a uint8 array holding 250 plus 10 gives 4, and an int8 127 plus 1 gives -128. Choose a wider dtype such as int64 or cast before the operation. Floats cannot be compared with == after arithmetic, since 0.1 + 0.2 is not exactly 0.3; use np.isclose or np.allclose with tolerances. Also remember that np.nan == np.nan is False, so use np.isnan.
pythona = np.array([250], dtype=np.uint8) print(a + np.uint8(10)) # [4] print(np.isclose(0.1 + 0.2, 0.3)) # True13 How do you handle NaN values in numeric arrays?
easyOrdinary reductions propagate NaN, so np.mean([1, np.nan, 3]) is nan. Use the nan-aware versions np.nanmean, np.nansum, np.nanmax, which skip NaN and give 2.0 for the example. Detect with np.isnan, and replace with np.nan_to_num or masked assignment. Remember to decide whether a missing value should be dropped, filled or kept before computing statistics, because skipping NaN changes the sample size.
14 Generate reproducible random data and a train/test split.
easyCreate a Generator with a seed, which is the modern approach, and use a permutation of indices for the split. Seeding fixes the sequence, so results are reproducible. Pass the generator around rather than seeding a global state. For classification, use a stratified split from scikit-learn when class balance matters.
pythonrng = np.random.default_rng(42) X = rng.normal(size=(100, 3)) idx = rng.permutation(len(X)) train, test = X[idx[:80]], X[idx[80:]]
Frequently asked questions
How much numpy is expected in a data science interview?
Shapes, broadcasting, indexing, axis operations and basic linear algebra. Implementing a small algorithm such as k-means or linear regression with numpy is a common exercise.
Is numpy still relevant with pandas and PyTorch?
Yes. Both build on the same ideas, and PyTorch tensor shape rules follow numpy broadcasting closely.
How do I debug a shape error quickly?
Print the shape of every operand, write the expected shape next to each line, and check the axis argument. Most errors are a missing reshape or a wrong axis.
What should I know about numpy performance?
Avoid Python loops over elements, preallocate arrays instead of appending, and watch for large temporary arrays created by broadcasting.
Related guides
More in Role-wise Interview Questions by Job and Tech Stack
- Pandas Interview Questions and Answers
- Performance Testing and JMeter Interview Questions
- Power BI Interview Questions and Answers
- Probability for Data Science Interview Questions and Answers
- Product Analyst Interview Questions and Answers
- PySpark Interview Questions and Answers
- React Hooks Interview Questions and Answers
- React Interview Questions and Answers (React 19)
- React Native Interview Questions and Answers
- Redux Interview Questions and Answers (Redux Toolkit)
- SDET Interview Questions and Answers
- Selenium Interview Questions and Answers