Skip to content
Tutorials Center
My learning

Topics

Lesson 48 of 49 ยท Practice and Review

Interview Questions

Prepare for data and Python interviews with common NumPy questions on views vs copies, broadcasting, axes, vectorization, dtypes and performance, with runnable answers.

NumPy shows up in interviews for data science, machine learning, quantitative and general Python roles. The questions are rarely about obscure functions. They test whether you understand a handful of core ideas: what an array really is, when memory is shared, how broadcasting works, what axis means, why vectorization is fast, and how data types can silently betray you.

This page collects the questions that come up most often, grouped by topic, with answers short enough to say aloud and code you can run to prove each claim. Interviewers like candidates who back a statement with a tiny experiment, so practice doing that. Related lessons are linked so you can revisit a topic you find shaky.

flowchart LR
    A["ndarray"] --> B["Memory<br/>views, copies, strides"]
    A --> C["Shapes<br/>broadcasting, axis"]
    A --> D["Types<br/>dtype, promotion, overflow"]
    A --> E["Speed<br/>vectorization, temporaries"]

The four areas that most NumPy interview questions come from.

Basics

1. Why is a NumPy array faster than a Python list?

A list stores pointers to separate Python objects scattered in memory, and every operation goes through the interpreter one element at a time. An ndarray stores raw numbers of one type next to each other in a single block, so loops run in compiled C code, the CPU can stream through memory efficiently, and modern processors can apply the same instruction to several numbers at once (SIMD). The array also needs less memory because there is no per-element object overhead. See What Is NumPy?.

2. What is the difference between shape, size, ndim and len?

shape is the tuple of dimension lengths, ndim is the number of dimensions (len(shape)), size is the total number of elements (the product of the shape), and len(arr) is the length of the first axis only.

Python shape, size, ndim and len

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

3. How do you create an array of a given shape filled with a value, and how is np.empty different?

np.zeros, np.ones and np.full(shape, value) initialize every element. np.empty allocates memory without initializing it, so the contents are whatever was there before. It is slightly faster, but only safe when you will overwrite every element before reading. See Creating Arrays.

Views and copies

4. What is a view, and when does NumPy return a view instead of a copy?

A view is a new array object that shares the same data buffer as another array. Basic slicing (a[1:5], a[::2], a[:, 0]), reshape (when possible), ravel (when possible), transposes and np.newaxis indexing return views. Advanced indexing (integer arrays, boolean masks), flatten, copy() and most arithmetic return copies. Changing a view changes the original.

Python Views, copies and shares_memory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

5. What is the difference between a = b, a = b.view() and a = b.copy()?

a = b creates no new array at all: both names refer to the same object. b.view() creates a new array object over the same data. b.copy() allocates new data. If asked how to find out, answer with is, np.shares_memory and the .base attribute. See Views vs Copies.

6. What is the difference between ravel() and flatten()?

Both return a 1D array. flatten() always returns a copy. ravel() returns a view when it can (for a C-contiguous array) and a copy otherwise. Prefer ravel() for speed when you only read the result, and flatten() when you will modify it and must not affect the original.

Broadcasting and axes

7. State the broadcasting rules.

Compare the shapes from the last axis backwards. Two dimensions are compatible if they are equal or one of them is 1; a missing dimension counts as 1. Size-1 axes are stretched virtually (no copy is made) to match the other array. If any pair is incompatible, NumPy raises a ValueError. See Broadcasting.

Python Broadcasting shapes and errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

8. What does axis mean in sum(axis=0)?

The axis you name is the one that is collapsed. For a 2D array, axis=0 combines rows downwards and returns one value per column; axis=1 combines across columns and returns one value per row. A reliable memory aid: the shape loses the axis you pass. keepdims=True keeps it as a length-1 axis so the result still broadcasts against the original. See Aggregations and Axes.

Python axis and keepdims

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

9. How do you add a dimension to an array?

Index with np.newaxis (an alias of None), as in a[:, None] or a[None, :], or call np.expand_dims(a, axis) or reshape. Adding axes is the usual way to make shapes broadcast. See Reshaping Arrays.

Vectorization

10. What is vectorization, and why does it matter?

Vectorization means expressing an operation on whole arrays so the loop happens inside NumPy's compiled code instead of in Python bytecode. A vectorized expression is typically 10 to 100 times faster than the equivalent Python loop and also shorter. See Vectorized Operations.

Python Loop versus vectorized result

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

11. Does np.vectorize make code fast?

No. np.vectorize is a convenience wrapper that still calls your Python function once per element; the documentation itself says it is provided for convenience, not performance. Real speed comes from using built-in ufuncs and array expressions, or from tools like Numba when you cannot avoid a custom loop. See Writing Fast NumPy Code.

12. What is a ufunc?

A universal function is a function such as np.add, np.sqrt or np.exp that operates elementwise on arrays, supports broadcasting and type casting, and offers extras like out=, where=, reduce, accumulate and outer.

Data types

13. What happens when an integer array overflows?

Integer arrays have a fixed width, and arithmetic wraps around silently. A uint8 can hold 0 to 255, so 250 + 10 becomes 4. NumPy 2 raises an error if you try to put a Python integer that does not fit into the type (for example np.uint8(300)), but results of array arithmetic still wrap. Choose a wider dtype if sums can grow. See Data Types.

Python Overflow and type promotion

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

14. What is the dtype of np.array([1, 2.5, True]) and np.array([1, "a"])?

NumPy picks the smallest type that can hold everything: floats win over integers and booleans, so the first is float64. Mixing numbers with strings produces a string dtype such as <U21, which is rarely what you want.

15. What is the difference between astype and view?

astype converts values and creates a new array (for example 3.7 becomes 3 when cast to int, truncating toward zero). view(dtype) reinterprets the same bytes as a different type without converting anything, which is almost never what a beginner wants. See Converting and Casting Types.

Floating point and comparisons

16. Why does np.array([0.1 + 0.2]) == 0.3 give False, and what should you use?

Binary floating point cannot represent most decimals exactly, so tiny rounding errors appear. Compare with a tolerance: np.isclose(a, b) elementwise or np.allclose(a, b) for the whole array. Also remember np.nan == np.nan is False; use np.isnan. See Comparing Arrays and Floating Point.

17. Why does if arr: or a > 1 and a < 5 raise "truth value of an array is ambiguous"?

Python's if, and, or and not need a single True/False, but an array comparison gives many. Use arr.any() or arr.all() for a single answer, and &, |, ~ with parentheses for elementwise logic.

Python Floats, NaN and the ambiguous truth value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Practical coding questions

18. How do you remove duplicates while counting occurrences?

np.unique(arr, return_counts=True) returns the sorted unique values and how often each appears. Use return_inverse=True to map each original element to its unique value's index. See Unique Values, Sets and Counting.

19. How do you find the index of the maximum, and what about ties?

arr.argmax() returns the flat index of the first maximum. For a 2D array, convert with np.unravel_index(arr.argmax(), arr.shape). All maxima: np.flatnonzero(arr == arr.max()).

20. How do you sort one array by another?

Compute order = keys.argsort() and index with it: values[order]. Use kind="stable" when equal keys must keep their original order, and np.lexsort for multiple keys (the last key is the primary one). See Sorting and Searching.

Python argsort, unique counts and unravel_index

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

21. How do you make results reproducible with random numbers?

Create a generator with a seed: rng = np.random.default_rng(42) and draw from it (rng.random(), rng.integers(), rng.normal()). The legacy np.random.seed and np.random.rand use hidden global state and are discouraged in new code. See Random Numbers with Generators.

Performance

22. What makes NumPy code slow, and how do you speed it up?

Common causes are Python-level loops over elements, growing arrays inside a loop with np.append or concatenate (each call copies everything), unnecessary copies and temporaries, the wrong dtype (float64 where float32 is enough, or object arrays), and non-contiguous memory access. Fixes: vectorize, preallocate with np.empty and fill, use in-place operators (a += b, np.multiply(a, b, out=a)), pick the right dtype, and measure with timeit before optimizing. See Writing Fast NumPy Code.

23. How do you reduce memory use of a big array?

Use a smaller dtype (float32, int16, uint8), avoid copies by using views and in-place operations, process the data in chunks, and use np.memmap for arrays larger than memory.

Python Preallocation and dtype memory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

24. What does the out= parameter do?

It writes the result into an existing array instead of allocating a new one, for example np.add(a, b, out=a). This saves memory and allocation time, but be careful: it overwrites the target, and the target must have a compatible dtype.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which of these returns a view of the original array?

    Basic slicing returns a view. Integer-array indexing, boolean masks and flatten() all return copies.
  2. 2. Shapes (3, 1) and (4,) are combined with +. What is the result shape?

    Aligning from the right: 1 stretches to 4, and the missing leading axis of (4,) counts as 1 which stretches to 3. The result is (3, 4).
  3. 3. What is np.array([250], dtype=np.uint8) + 10?

    A uint8 holds 0 to 255. Array arithmetic keeps the dtype and wraps modulo 256, silently: 260 becomes 4.
  4. 4. Does np.vectorize make a slow Python function fast?

    np.vectorize is a convenience wrapper around a Python loop. Real speedups come from built-in ufuncs, array expressions or compilers such as Numba.
  5. 5. arr.sum(axis=0) on an array of shape (5, 3) returns an array of which shape?

    axis=0 is collapsed, leaving the remaining axis of length 3: one sum per column.

Summary

  • Know why arrays are fast: contiguous typed memory and compiled loops instead of Python objects.
  • Slicing makes views, fancy and boolean indexing make copies; prove it with np.shares_memory.
  • Broadcasting aligns shapes from the right; axis names the axis that disappears; keepdims=True keeps results broadcastable.
  • Integer arrays wrap around on overflow; compare floats with isclose, never ==.
  • Use default_rng for reproducible randomness, and np.vectorize is not a speed tool.
  • For performance: vectorize, preallocate, avoid temporaries, choose small dtypes, and measure first.

Finish the track with the NumPy Cheat Sheet.