NumPy interview questions and answers
NumPy interview questions test whether you can think in whole arrays instead of Python loops: choosing dtypes, predicting shapes, vectorizing an algorithm with broadcasting, and knowing when an operation copies memory. Senior rounds add floating point traps, numerical stability, strides and memory limits. Expect a live task such as rewriting a nested loop, computing distances or writing a stable softmax, with follow-up questions about why your version is fast and correct.
By Evin JohnPublished 9 min read
Where NumPy questions come up
NumPy sits under pandas, scikit-learn, SciPy and most Python ML code, so interviewers use it to see what you understand below the library calls. Machine learning and research engineering loops ask it most, followed by quant developer roles, computer vision teams and scientific software groups. Data analyst rounds lean on pandas instead and only touch NumPy lightly.
- Quick concept checkFive to ten minutes of short questions: what a dtype is, what
axis=1returns, whya == np.nanfails, what a view is. - Vectorize thisYou get a working loop, often a distance, a moving statistic or a histogram, and you rewrite it with array operations. Interviewers watch the shapes you choose.
- Correctness and scaleFollow-ups about overflow, precision, memory for large inputs and whether your result matches the loop on edge cases such as empty arrays or ties.
- Implement from scratchCommon in ML loops: softmax, cross-entropy, k-means, k-nearest neighbors, linear regression with the normal equation or a simple gradient step, using only NumPy.
NumPy fundamentals questions
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What does an ndarray store besides the numbers? | Array model | A pointer to a data buffer, a dtype, a shape and strides. Shape says how many items per dimension; strides say how many bytes to jump to reach the next one. |
What is the difference between shape, ndim and size? | Basics | shape is a tuple of lengths per dimension, ndim is how many dimensions there are, and size is the total element count, the product of the shape. |
np.arange or np.linspace for float ranges? | Construction | linspace takes a count and includes the end, so the length is exact. arange with a float step can gain or lose an element through rounding, so keep it for integers. |
When is np.empty safe to use? | Allocation | Only when every element is written before it is read. It skips zero-filling, so the buffer holds whatever bytes were in memory. |
What does reshape(-1) mean, and when does reshape fail? | Shapes | -1 asks NumPy to infer one dimension from the total size. It fails when the sizes do not divide, for example 10 elements into rows of 3. |
ravel versus flatten? | Copies | flatten always returns a new array. ravel returns a view when the memory layout allows and copies only when it must, so writing to its result may or may not touch the original. |
What shape does a.sum(axis=0) return for a (4, 3) array? | Axis | A (3,) array: the axis you name disappears. With keepdims=True you get (1, 3), which broadcasts back against the original without a reshape. |
| How do you add a new axis? | Dimensions | a[:, None] or a[:, np.newaxis] turns a (n,) vector into (n, 1). np.expand_dims does the same with an explicit axis number. |
| How do you count values that meet a condition? | Masks | np.count_nonzero(a > 0) or (a > 0).sum(), since True counts as 1. np.mean(a > 0) gives the share. |
What does np.where(cond) return with only one argument? | Indices | A tuple of index arrays, one per dimension, the same as np.nonzero. With three arguments it chooses between two values element by element. |
concatenate, stack, vstack or hstack? | Combining | concatenate joins along an existing axis. stack creates a new axis, so inputs must share a shape. vstack treats 1D inputs as rows; hstack joins 1D inputs end to end and 2D inputs side by side. |
| How does sorting treat NaN? | Edge cases | np.sort places NaN at the end. argsort follows the same rule. Mention it when a task asks for the smallest values in data that may contain gaps. |
Dtypes, overflow and floating point
A large share of NumPy bugs come from the dtype, not the logic. Fixed-width integers wrap around instead of growing like Python ints, and floats cannot store most decimals exactly. Interviewers like to show a surprising output and ask you to explain it.
import numpy as np
a = np.array([120, 7], dtype=np.int8)
print(a + a) # [-16 14]: int8 wraps around silently
print(0.1 + 0.2 == 0.3) # False
print(np.isclose(0.1 + 0.2, 0.3)) # True
x = np.float32(16_777_217)
print(int(x)) # 16777216: float32 has a 24-bit significand
# NumPy 2 promotion (NEP 50): Python scalars are "weak" and adapt to NumPy types
print((np.float32(3) + 3.0).dtype) # float32 (NumPy 1.x gave float64)
try:
np.uint8(1) + 300 # 300 does not fit in uint8
except OverflowError:
print("OverflowError")- Image pixels are uint8. Why does adding two images look wrong? Values above 255 wrap around. Convert to a wider type first, for example
img.astype(np.int16), then clip back to 0 to 255 before casting down. - When would you pick float32 over float64? For large ML tensors and GPU work where memory and bandwidth matter more than the last digits. Keep float64 for accumulating long sums, solving linear systems and financial calculations.
- How do you compare float arrays in a test?
np.allcloseornp.testing.assert_allclosewith a stated tolerance. Explain thatrtolscales with the size of the values andatolhandles numbers near zero. - What changed in type promotion with NumPy 2? Python scalars became "weak": they adapt to the array's dtype instead of upcasting it, and a value that cannot fit raises an error. Code that relied on silent upcasting can change results, so mention reading the migration guide for the version your team runs.
- Why is `np.array([1, 2, 'a'])` a problem? NumPy finds one common dtype, here a string type, so the numbers become text and arithmetic fails. Mixed records belong in a structured array, a DataFrame or plain Python objects.
- How do you read big-endian binary data such as a network header? Give the dtype a byte order:
np.frombuffer(buf, dtype='>u2')reads 16-bit unsigned values in network order, so the bytes01 bb 00 50become 443 and 80.
Memory layout, strides and views
Senior candidates are expected to explain why some operations are free and others copy. The answer is strides: many reshapes, transposes and slices only build a new header over the same buffer.
import numpy as np
m = np.arange(12, dtype=np.int64).reshape(3, 4)
print(m.strides) # (32, 8): next row is 32 bytes on, next column 8
t = m.T
print(t.strides, np.shares_memory(m, t)) # (8, 32) True: transpose swaps strides
print(t.flags["C_CONTIGUOUS"]) # False
print(np.shares_memory(m, m.ravel()), np.shares_memory(t, t.ravel()))
# True False: ravel returns a view when it can and copies when it must
from numpy.lib.stride_tricks import sliding_window_view
s = np.array([1, 3, 2, 6, 4])
w = sliding_window_view(s, 3) # read-only view of shape (3, 3), nothing copied
print(w.mean(axis=1).round(2).tolist()) # [2.0, 3.67, 4.0]| Question | What it tests | What a strong answer shows |
|---|---|---|
| C order versus Fortran order? | Layout | C order keeps the last index contiguous, so walking along a row is cache friendly. Fortran order keeps the first index contiguous. Some LAPACK routines and older libraries prefer Fortran layout. |
| Why can summing along one axis be faster than along another? | Cache | Reading contiguous memory uses whole cache lines. Striding across rows of a large C-ordered array jumps through memory and wastes bandwidth. |
When would you call np.ascontiguousarray? | Interop | Before handing an array to C code, a GPU copy or a library that expects contiguous memory, or before a hot loop over a transposed view. |
What is the risk with as_strided? | Safety | It trusts the strides you give it. A wrong value reads memory outside the buffer and can return garbage or crash. sliding_window_view is the safer choice for windows. |
| Why might deleting a big array not free memory? | Ownership | A small slice taken from it is a view that keeps the whole buffer alive. Copy the slice with .copy() if you only need that part. |
Vectorization and indexing questions
The most common live task: replace a loop with array operations. Write the shape of each intermediate next to the line, because that is what the interviewer is checking.
import numpy as np
rng = np.random.default_rng(7)
points = rng.random((5, 2)) # 5 points in 2D
queries = rng.random((3, 2)) # 3 query points
# (3, 1, 2) - (1, 5, 2) broadcasts to (3, 5, 2): every query against every point
diff = queries[:, None, :] - points[None, :, :]
dist = np.sqrt((diff ** 2).sum(axis=-1)) # shape (3, 5)
# Two nearest points per query without a full sort
k = 2
idx = np.argpartition(dist, k, axis=1)[:, :k] # unordered k smallest
order = np.take_along_axis(dist, idx, axis=1).argsort(axis=1)
nearest = np.take_along_axis(idx, order, axis=1) # sorted by distance
print(dist.shape, nearest.shape) # (3, 5) (3, 2)
check = np.argsort(dist, axis=1)[:, :k]
print(np.array_equal(nearest, check)) # True
# Duplicate indices: fancy += applies once per unique index, np.add.at applies all
counts = np.zeros(4, dtype=int)
hits = np.array([0, 2, 2, 3, 2])
counts[hits] += 1
print(counts.tolist()) # [1, 0, 1, 1]
counts = np.zeros(4, dtype=int)
np.add.at(counts, hits, 1)
print(counts.tolist()) # [1, 0, 3, 1]
print(np.bincount(hits, minlength=4).tolist()) # [1, 0, 3, 1]| Question | What it tests | What a strong answer shows |
|---|---|---|
Why does counts[idx] += 1 undercount when idx repeats? | Buffered fancy assignment | The right side is computed once and written back, so each repeated index is written once. Use np.add.at or np.bincount when indices repeat. |
| argsort or argpartition for the top 10 of a million values? | Selection | argpartition finds the k smallest or largest in linear time without ordering them. Sort only those k afterwards. A full argsort costs n log n for order you do not need. |
What does np.einsum do, and when is it worth it? | Expressiveness | It writes sums of products with index letters: ij,jk->ik is a matrix product, ii-> a trace, bij,bjk->bik a batched product. It is clear for odd contractions; for plain products @ is usually as fast or faster. |
What are ufunc methods such as reduce, accumulate and outer? | Ufuncs | Every binary ufunc has them: np.add.reduce is a sum, np.maximum.accumulate a running max, np.subtract.outer builds every pairwise difference. |
| How do you bucket values into ranges? | Binning | np.digitize or np.searchsorted against sorted edges, then np.bincount on the bucket ids for counts. Say which side of each edge is inclusive. |
| How do you count unique values? | Counting | np.unique(a, return_counts=True). For small non-negative integers, np.bincount is faster and keeps zero counts. |
| How do you avoid temporary arrays in a hot path? | Memory | Pass out= to ufuncs or use in-place operators such as a *= 2, as long as the dtype stays the same and nothing else depends on the old values. |
What does take_along_axis solve? | Index alignment | It gathers values using an index array shaped like the output of argsort or argpartition, so you can pick per-row elements without building row indices by hand. |
How does np.vectorize perform? | Myth check | It is a convenience wrapper around a Python loop, not real vectorization. Speed comes from expressing the logic with ufuncs and broadcasting. |
Linear algebra and randomness
import numpy as np
def softmax(z, axis=-1):
z = z - z.max(axis=axis, keepdims=True) # shift so the largest value is 0
e = np.exp(z)
return e / e.sum(axis=axis, keepdims=True)
logits = np.array([[1000.0, 1001.0, 1002.0],
[1.0, 2.0, 3.0]])
with np.errstate(over="ignore", invalid="ignore"):
naive = np.exp(logits) / np.exp(logits).sum(axis=1, keepdims=True)
print(naive[0].tolist()) # [nan, nan, nan]: exp(1000) overflowed
print(softmax(logits).round(3).tolist()) # [[0.09, 0.245, 0.665], [0.09, 0.245, 0.665]]
A = np.array([[3.0, 1.0], [1.0, 2.0]])
b = np.array([9.0, 8.0])
print(np.linalg.solve(A, b).tolist()) # [2.0, 3.0]; prefer solve to inv(A) @ b
print(np.einsum("ij,j->i", A, [2.0, 3.0]).tolist()) # [9.0, 8.0]- Why use `np.linalg.solve` instead of computing the inverse? It factorizes once and solves directly, which is faster and loses less precision. An explicit inverse is rarely needed.
- The system has more equations than unknowns. What now?
np.linalg.lstsqgives the least squares solution and reports rank, which tells you whether columns are collinear. - How do you tell that a matrix is close to singular? A determinant near zero is a weak signal because it scales with the matrix. Check
np.linalg.cond: a very large condition number means small input errors produce large output errors. - `eig` or `eigh`?
eighis for symmetric or Hermitian matrices such as covariance matrices. It is faster and returns real, sorted eigenvalues, whereeigcan return tiny imaginary parts from rounding. - How does `@` treat 3D arrays? It treats the leading dimensions as a batch and multiplies the last two, broadcasting the batch dimensions.
np.dotfollows a different rule for higher dimensions, which surprises people. - How do you write log-sum-exp safely? Subtract the max before exponentiating and add it back after the log, the same shift as in the softmax above. Cross-entropy built on raw
expoverflows on large logits. - How should random numbers be generated now? Create a
Generatorwithnp.random.default_rng(seed)and pass it into functions. For parallel workers, spawn independent streams withSeedSequenceinstead of giving each worker seed plus one.
Senior and scenario questions
| Question | What it tests | What a strong answer shows |
|---|---|---|
| Your broadcast distance code runs out of memory on 100k points. Why? | Intermediate size | The (n, m, d) difference array is the problem, not the output. Expand the squared distance as a squared norm minus twice a dot product plus another norm, which needs only (n, m), and process queries in chunks. |
| That squared-norm trick gave a tiny negative distance. Why? | Cancellation | Subtracting two large, nearly equal numbers loses precision. Clip at zero before the square root, and use float64 if the points are close together. |
| The array is bigger than RAM. Options? | Out of core | np.memmap or np.load(mmap_mode='r') reads pages on demand. Process in chunks that fit, or move to a tool built for it such as Dask or a database. |
| When is NumPy the wrong tool for a loop? | Limits | When each step depends on the previous one, such as a custom recurrence, vectorization may not apply. A compiled approach such as Numba or Cython, or a library routine, can fit better. |
| Does NumPy use multiple cores? | Threads | Elementwise ufuncs run on one thread. Matrix products and decompositions call a BLAS library that is usually multithreaded, which can oversubscribe cores when you also run worker processes. |
| How would you test a vectorized rewrite? | Verification | Keep the slow loop as a reference, run both on random inputs including empty, single-element and tied cases, and compare with assert_allclose. Then time both on realistic sizes. |
| What should you check when upgrading to NumPy 2? | Version awareness | Promotion rules for scalars, removed aliases such as np.float_, changes to the C API for compiled extensions, and whether every dependency ships builds for the new major version. |
Fictional example
- Interviewer
- This function loops over every query and every training point to find the five nearest. It takes minutes. Speed it up with NumPy.
- Candidate
- Queries are (q, d) and training points are (n, d). I will insert axes so the difference is (q, n, d), sum squares over the last axis to get (q, n), then use argpartition with k equal to 5 along axis 1 and sort just those five. Before timing it, I will run the old loop on twenty random points and compare indices, including a case with two points at the same distance, since ties may come back in a different order.
- Interviewer
- Training data grows to two million rows.
- Candidate
- Then the (q, n, d) block will not fit. I would switch to the squared-norm expansion so the biggest temporary is (q, n), run queries in batches of a few hundred, and use float32 if the accuracy check still passes. Past that size I would reach for a tree or an approximate nearest neighbor index rather than brute force.
A one-week NumPy practice plan
- Day 1: dtypes and shapes. Predict the dtype and shape of twenty expressions before running them.
- Day 2: broadcasting drills. Center columns, scale rows, build a multiplication table and compute pairwise distances, writing shapes beside each line.
- Day 3: indexing. Boolean masks, fancy indexing,
take_along_axis, and the repeated-index trap withnp.add.at. - Day 4: from scratch. Softmax, cross-entropy, a linear regression with
lstsqand a k-means step. - Day 5: precision. Floats that fail equality, uint8 overflow, a stable log-sum-exp and a near-singular system.
- Day 6: layout and memory. Strides, views versus copies,
memmapand a chunked computation on a large array. - Day 7: a timed mock: vectorize a loop in 25 minutes, test it against the original, then explain the speedup in two minutes.
NumPy rarely gets a round of its own. It shows up inside machine learning interview questions, next to pandas interview questions in data loops, and in data scientist interview questions whenever a modeling task needs code.
Vectorizing a loop out loud is a skill of its own, and most people only find out how they explain shapes when they hear themselves. Natively is an AI interview assistant for Mac and Windows that can transcribe a practice session on your computer, so you can review where you went quiet or skipped the shape check. While you practice, it can read a task, an error or a wrong output from a screenshot and suggest a vectorized version to compare with yours. With Pro or the free trial it can use the résumé and job description you add, and the transcript and notes stay saved for later.
Questions people ask
What NumPy questions are asked in interviews?
Expect questions on dtypes and shapes, the axis argument, broadcasting, views versus copies, fancy indexing, argsort and argpartition, linear algebra with solve and lstsq, random generators and floating point precision, plus a live task to vectorize a loop.
How do I answer NumPy broadcasting questions?
Compare shapes from the last dimension backwards: sizes must match or one must be 1. Then write the shape of every intermediate array, because interviewers check that more than the final line.
Are NumPy interview questions different for freshers and experienced candidates?
Freshers get array creation, shapes, axis and masks. Experienced candidates get strides and memory layout, overflow and precision bugs, stable formulas such as softmax, and memory limits on large inputs.
How should I practice NumPy for a machine learning interview?
Implement softmax, cross-entropy, k-means and nearest neighbors with arrays only, test each against a slow loop, then time both versions and explain the difference out loud.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
