NumPy Arrays & Vectorization
Create ndarrays, avoid Python loops, and use vectorized ops for fast numerical computing.
In plain words
NumPy lets you do maths on a whole list of numbers in one go, which is much faster than going through them one at a time.
Think of it like…
A spreadsheet column versus a person reading values aloud one by one: the spreadsheet applies a formula to the whole column at once, in optimised code, while the person (a Python loop) handles each cell separately with overhead each time.
Where you’ve seen it
A pricing script computes a discounted price for 5 million rows with a Python loop and takes 4 seconds. The vectorized np.where(qty >= 100, price * 0.9, price) does the same in about 25 milliseconds. Changing the dtype from float64 to float32 halves the memory of the price array (40 MB to 20 MB), and the downstream model doesn't need the extra precision.
Words you’ll hear
- ndarray
- Homogeneous N-dimensional array with a fixed dtype and shape.
- Vectorization
- Applying an operation to a whole array in compiled code instead of looping in Python.
- dtype
- The element type (int64, float32, bool); fixed per array.
- View vs copy
- Slices are views sharing memory; fancy or boolean indexing returns copies.
Visual diagram
Theory & deep dive
Creating arrays and understanding shape and dtype
Create arrays with np.array([1, 2, 3]), np.zeros((3, 4)), np.arange(0, 10, 2), np.linspace(0, 1, 5) and np.random.default_rng(42).normal(size=1000). a.shape, a.ndim, a.dtype and a.nbytes describe an array; a.reshape(2, -1) changes the dimensions without copying data (the -1 means "infer this length"). Arrays hold one dtype: mixing ints and floats upcasts to float, and mixing numbers and strings produces a string array.
dtype affects results. Integer types overflow silently (an int8 array holds -128 to 127, so 127 + 1 wraps to -128), division of ints gives floats with / but floors with //, and float comparisons need tolerance (np.isclose). Pick float32 when memory matters and precision allows, int32 for ids, bool for masks and category-like codes as small integers.
a = np.arange(12, dtype=np.float32).reshape(3, 4) gives shape (3, 4), 12 elements, and a.nbytes == 48 (12 × 4 bytes), where float64 would need 96.
Vectorized operations and avoiding loops
Arithmetic, comparisons and universal functions work element by element across whole arrays: (a - a.mean()) / a.std() standardises a column, a > 0 returns a boolean mask, and a[a > 0] selects values. Aggregations take an axis: m.sum(axis=0) sums down each column, axis=1 across each row. np.where(cond, x, y) is the vectorized if/else, np.clip, np.cumsum and np.diff cover many common loops.
When you must conditionally transform, express it with masks and np.where rather than a loop; when logic truly can't be vectorized, consider np.vectorize (a convenience, not a speed-up), Numba or moving to pandas methods. Beware of making huge temporary arrays: a * b + c creates intermediate arrays, which np.einsum, in-place operators (a *= 2) or chunking can reduce. Slicing returns a view, so modifying a slice modifies the original; use .copy() when you need independence.
mask = (qty >= 100) & (region == 3); price[mask] *= 0.9 applies the discount to qualifying rows only, in place, with no Python loop. Use & and | with parentheses, not and / or.
np.where; remember axis and views vs copies.How it works, step by step
Step 1 of 41. Check shape and dtype
Print shape, dtype and nbytes before computing so assumptions about size and type are explicit.
- First
- look at these three
When to use it & trade-offs
What it is
A NumPy ndarray is a fixed-type, N-dimensional block of numbers stored contiguously in memory. Operations on whole arrays, such as a * 2 + b or np.sqrt(a), run in compiled C loops instead of Python loops; this is vectorization. Every array has a shape (its dimensions) and a dtype (its element type, like float64 or int32), and choosing both well decides speed and memory.
Why it matters: Pandas, scikit-learn, PyTorch and SciPy all sit on arrays, and a Python for loop over a million numbers can be 50 to 100 times slower than the equivalent array expression. Understanding shape and dtype also explains common bugs: silent integer overflow, unexpected float rounding, or an array of shape (n,) behaving differently from (n, 1).
When to reach for it
- Numerical transformations on columns and matrices
- Masks for conditional logic
- Preparing arrays for scikit-learn and PyTorch
When to avoid or be careful
- Python loops over large arrays
- Silent dtype overflow with small integer types
- Using
and/orinstead of&/|on masks
Ways to compute over many numbers
Strengths: Flexible and easy to read for tiny inputs.
Watch out: Slow on large data due to per-item overhead.
Strengths: Compiled speed, concise code, rich functions.
Watch out: Whole-array temporaries use memory; single dtype.
Strengths: Near-C speed for custom logic.
Watch out: Extra dependency and constraints on code.
Interview signals & numbers to know
When this topic comes up
- “Why is this loop so slow?”
- “What does axis=0 mean?”
- “Why did my array change when I changed a slice?”
- Views vs copies
- Memory and dtype choices
Benchmarks & rules of thumb
- 50 – 100×
- typical speed-up over Python loops
- 8 → 4 bytes
- float64 → float32
- axis 0 / 1
- down columns / across rows
Common mistakes & follow-ups
Common interview mistakes
- Writing
if a > 0:on an array and getting a truth-value error; use a mask ornp.any/np.all. - Modifying a slice and being surprised that the original array changes (it's a view).
- Storing counts in
int8and overflowing at 127.
Likely interviewer follow-ups
- What is vectorization and why is it faster?
- What's the difference between a view and a copy?
- How do you apply an if/else across an array without a loop?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply NumPy Arrays & Vectorization with data science interview Q&A and hands-on practice.