Data Structures
NumPy ndarray — Complete Beginner to Interview Guide
Learn NumPy arrays from scratch: what they are, every important method explained one by one with output, broadcasting explained visually, and interview patterns.
- Python
- NumPy
- DSA
- Data Structures
- Algorithm
1. What is NumPy?
Points to understand first:
- NumPy stands for Numerical Python.
- It is a third-party library — you install it with
pip install numpybefore using it. - Its main feature is the ndarray (n-dimensional array) — a fast, memory-efficient, multi-dimensional array.
- Unlike a Python
list, a NumPy array stores only one data type, as raw contiguous memory — this is what makes it so fast. - NumPy lets you do math on an entire array at once, without writing a manual loop — this is called vectorization.
- Almost every major Python data-science and machine-learning library (pandas, scikit-learn, PyTorch) is built on top of NumPy.
2. Why is NumPy Faster Than a Python List?
3. Key Attributes of an Array
| attribute | meaning |
|---|---|
| shape | A tuple showing the size of each dimension, e.g. (3, 4) |
| ndim | How many dimensions the array has (1 = a list, 2 = a table, ...) |
| size | The total number of elements in the array |
| dtype | The data type of every element, e.g. int64, float64 |
| itemsize | How many bytes each element uses |
| T | The transposed version of the array (rows and columns swapped) |
4. Creating Arrays — Every Way, One by One
4.1 np.array() — From a Python List
4.2 np.zeros() — An Array Full of Zeros
4.3 np.ones() — An Array Full of Ones
4.4 np.full() — An Array Filled With a Chosen Value
4.5 np.eye() — An Identity Matrix
4.6 np.arange() — Like Python’s range(), but Returns an Array
4.7 np.linspace() — Evenly Spaced Numbers
4.8 np.random.rand() and np.random.randint() — Random Arrays
4.9 np.zeros_like() — Same Shape as Another Array
5. Indexing and Slicing
5.1 Basic Indexing (1-D Array)
5.2 Indexing a 2-D Array (Matrix)
5.3 Boolean Masking — Picking Items by Condition
Points:
- You can compare a whole array to a value — this gives back an array of
True/False. - You can then use that
True/Falsearray to filter the original array. - This is one of the most useful NumPy tricks, used constantly in real code and interviews.
5.4 Fancy Indexing — Picking Multiple Specific Positions
6. Views vs Copies — An Important Beginner Trap
Points:
- Basic slicing (
a[1:3]) gives you a view — it shares the same memory as the original array. - Changing a view also changes the original array!
- Use
.copy()when you need a completely independent array.
7. Reshaping and Combining Arrays
7.1 reshape() — Change the Shape Without Changing the Data
7.2 flatten() vs ravel() — Back to 1-D
7.3 T — Transpose (Swap Rows and Columns)
7.4 np.concatenate(), np.vstack(), np.hstack() — Combining Arrays
8. Vectorized Math — The Whole Point of NumPy
Points:
- “Vectorized” means you can apply an operation to every element at once, with no explicit loop.
- This is both shorter to write and much faster to run than a Python
forloop.
9. Broadcasting — Combining Different Shapes
Broadcasting is how NumPy applies an operation between two arrays of different shapes, without you writing a loop.
The rule (simplified):
- Compare the shapes of the two arrays, starting from the right side.
- Two dimensions are compatible if they are equal, or if one of them is 1.
- NumPy “stretches” the smaller dimension to match — without actually copying data in memory.
10. Every Common Method — Explained One by One
10.1 np.sort() / a.sort() — Sorting
10.2 argsort() — Get the Sorted Indices
Why this matters: sometimes you need to know where the sorted values came from, not just the sorted values themselves.
10.3 sum(), mean(), std(), var()
10.4 min(), max(), argmin(), argmax()
10.5 np.unique() — Unique Values, Sorted
10.6 np.where() — Conditional Selection
10.7 cumsum() — Running (Cumulative) Sum
10.8 any() and all()
10.9 astype() — Convert to a Different Data Type
10.10 sum(axis=...) — Summing Along Rows or Columns
Points:
- For 2-D arrays,
axis=0means “go down the columns.” axis=1means “go across the rows.”- This confuses almost every beginner at first — the diagram below should help.
11. All Methods in One Table (Quick Reference)
| method | what it does |
|---|---|
| reshape(shape) | Return a view with a new shape |
| flatten() / ravel() | Collapse to 1-D (copy vs view) |
| sort() / np.sort(a) | Sort in place / return a new sorted array |
| argsort() | Indices that would sort the array |
| sum() / mean() / std() / var() | Total, average, standard deviation, variance |
| min() / max() | Smallest / largest value |
| argmin() / argmax() | Index of the smallest / largest value |
| np.unique(a) | Sorted unique values |
| np.where(cond, x, y) | Pick x or y based on a condition, elementwise |
| cumsum() | Running/cumulative sum |
| any() / all() | True if any / all elements are truthy |
| copy() | Independent copy of the array's data |
| astype(dtype) | Convert to a different data type |
| T | Transpose (swap rows/columns) |
12. A Worked Example Combining Several Concepts
13. Interview Patterns (Question First, Then Solution)
13.1 Pattern: Check if an Array is Sorted (Vectorized)
❓ Interview Question:
- Problem: Given a NumPy array, check whether it is sorted in ascending order — without writing a manual loop.
- Example:
- Input:
[1, 2, 2, 5] - Expected Output:
True - Input:
[1, 5, 2] - Expected Output:
False
- Input:
- Hint: Compare the array to a “shifted” version of itself.
✅ Approach:
- Compare every item (except the last) to the item right after it.
- If every item is less than or equal to its neighbor, the array is sorted.
np.all()checks that this is true for the entire array at once.
Complexity: Time = O(n), Space = O(n) for the comparison array.
13.2 Pattern: Find All Pairs That Sum to a Target (Vectorized Filtering)
❓ Interview Question:
- Problem: Given an array of numbers and a target sum, find how many numbers in the array are needed to reach the target when paired with a specific value — here, count how many values are “positive after subtracting the target.”
- Example:
- Input:
nums = [1, 2, 3, 4, 5],target = 3 - Expected Output: values greater than target →
[4, 5]
- Input:
- Hint: Boolean masking turns a filtering problem into one line.
✅ Approach:
- Build a boolean mask comparing the whole array to the target at once.
- Use that mask to select only the matching values.
Complexity: Time = O(n), Space = O(k) where k is the number of matches.
13.3 Pattern: Matrix Row and Column Sums (Common in Interviews)
❓ Interview Question:
- Problem: Given a 2-D matrix, find the sum of each row and the sum of each column.
- Example:
- Input:
[[1, 2, 3], [4, 5, 6]] - Expected Output: row sums
[6, 15], column sums[5, 7, 9]
- Input:
- Hint: This is exactly what the
axisparameter is for.
✅ Approach:
axis=1sums across each row.axis=0sums down each column.
Complexity: Time = O(rows × columns), Space = O(rows + columns).
14. NumPy vs list vs array — When to Use Which
| situation | best choice |
|---|---|
| Small, mixed-type collection, general logic | list |
| Need O(1) push/pop from both ends | collections.deque |
| Large numeric dataset, need fast math | numpy.ndarray |
| Need multi-dimensional arrays / matrix math | numpy.ndarray |
| Compact single-type binary buffer only | array.array |
15. Practice Problems (Try These Yourself)
- Given an array of exam scores, find how many students scored above the average.
- Write a function that reverses each row of a 2-D matrix.
- Given two arrays of the same shape, compute the elementwise maximum.
- Find the index of the closest value to a target number in an array.
- Compute the moving average of a 1-D array with a given window size.
16. Key Takeaways
numpy.ndarraystores one fixed data type, contiguously in memory — this is what makes it fast.- Vectorized operations (
a + b,a ** 2,np.sum(a)) replace manual loops and run much faster. - Basic slicing returns a view, not a copy — use
.copy()when you need independence. - Boolean masking (
a[a > 0]) and fancy indexing (a[[0, 2, 4]]) are the two most useful indexing tricks. - Broadcasting lets you combine arrays of different shapes without writing loops, following the “match or 1” rule.
axis=0means down the columns,axis=1means across the rows — a common beginner confusion worth memorizing.argsort,cumsum,where, anduniqueshow up constantly in interview questions about arrays.
10. Every Important Method — Explained One by One
10.1 np.sort() — Sort the Array
10.2 argsort() — Get the Indexes That Would Sort the Array
This one confuses beginners — here is the difference from sort():
sort()gives you the sorted values.argsort()gives you the indexes that would put the array in sorted order.
10.3 sum(), mean(), std(), var()
10.4 min(), max(), argmin(), argmax()
10.5 np.unique() — Get Unique Values, Sorted
10.6 np.where() — Choose a Value Based on a Condition
10.7 cumsum() — Running (Cumulative) Total
10.8 any() and all()
10.9 astype() — Convert to a Different Data Type
10.10 sum(axis=...) — Summing Along Rows or Columns
This trips up a lot of beginners with 2-D arrays:
axis=0means “go down the columns” — sum each column.axis=1means “go across the rows” — sum each row.
11. All Methods in One Table (Quick Reference)
| method | what it does |
|---|---|
| a.reshape(shape) | Return a view with a new shape (same data) |
| a.flatten() / a.ravel() | Collapse to 1-D (copy vs view) |
| np.sort(a) / a.sort() | Sort ascending (new array / in place) |
| a.argsort() | Indexes that would sort the array |
| a.sum() / a.mean() | Total / average of all elements |
| a.std() / a.var() | Standard deviation / variance |
| a.min() / a.max() | Smallest / largest value |
| a.argmin() / a.argmax() | Index of smallest / largest value |
| np.unique(a) | Sorted list of unique values |
| np.where(cond, x, y) | x where True, y where False |
| a.cumsum() | Running/cumulative sum |
| a.any() / a.all() | True if any/all elements are truthy |
| a.astype(dtype) | Convert to a different data type |
| a.copy() | Independent copy of the array's data |
12. Interview Patterns (Question First, Then Solution)
12.1 Pattern: Normalize a List of Scores (Min-Max Scaling)
❓ Interview Question:
- Problem: Given an array of numbers, rescale every value into the range
0to1. - Example:
- Input:
[65, 90, 72, 88, 55] - Expected Output: values between
0.0and1.0, where the smallest input becomes0.0and the largest becomes1.0.
- Input:
- Hint: Subtract the minimum, then divide by the range (max - min).
✅ Approach:
- Find the minimum and maximum values of the array.
- For every value: subtract the minimum (shifts the range to start at 0).
- Divide by
(max - min)(scales the range down to fit between 0 and 1).
Complexity: Time = O(n), Space = O(n) for the result array.
12.2 Pattern: Distance Between Two Points
❓ Interview Question:
- Problem: Given two points as arrays (e.g.
[x, y]), calculate the straight-line (Euclidean) distance between them. - Example:
- Input:
p1 = [0, 0],p2 = [3, 4] - Expected Output:
5.0
- Input:
- Hint: This is the same formula as the Pythagorean theorem: square the differences, add them, take the square root.
✅ Approach:
- Subtract the two points to get the difference in each dimension.
- Square every difference.
- Add the squares together, then take the square root of the total.
Complexity: Time = O(d) where d = number of dimensions, Space = O(1).
12.3 Pattern: Check if an Array is Sorted (Vectorized)
❓ Interview Question:
- Problem: Given an array, check whether it is sorted in ascending order — without writing a manual loop.
- Example:
- Input:
[1, 2, 2, 5] - Expected Output:
True - Input:
[1, 5, 2] - Expected Output:
False
- Input:
- Hint: Compare the array to a “shifted” version of itself.
✅ Approach:
- Compare every element (except the last) to the element right after it.
- If every one of those comparisons is
True(each item is less-than-or-equal to the next), the array is sorted. np.all()checks that every comparison passed.
Complexity: Time = O(n), Space = O(n) for the comparison array.
12.4 Pattern: Find All Pairs That Add Up to a Target (Using a Set)
❓ Interview Question:
- Problem: Given an array of numbers and a target sum, find all pairs of numbers that add up to the target.
- Example:
- Input:
nums = [2, 7, 11, 15, -2],target = 9 - Expected Output:
[(2, 7)]
- Input:
- Hint: For each number, check whether
target - numberhas already been seen.
✅ Approach:
- Keep a
setof numbers seen so far. - For each number, calculate what its “partner” would need to be (
target - number). - If that partner is already in the seen set, you found a pair.
- Add the current number to the seen set, then move on.
Complexity: Time = O(n), Space = O(n) for the seen set.
13. Practice Problems (Try These Yourself)
- Given a 2-D array, find the sum of its diagonal elements.
- Given an array of temperatures, count how many days were above the average.
- Given two arrays of the same shape, compute their element-wise product (not the dot product).
- Reverse a 2-D array both horizontally and vertically.
- Find the index of the closest value to a given number in an array.
14. NumPy vs list vs array — When to Actually Use It
| situation | best choice |
|---|---|
| Small, mixed-type collection, general logic | list |
| Need O(1) push/pop from both ends | collections.deque |
| Large numeric dataset, need math (sum, mean, matrix ops) | numpy.ndarray |
| Need multi-dimensional arrays / linear algebra | numpy.ndarray |
| Compact single-type binary buffer, no numeric operations | array.array |
15. Key Takeaways
numpy.ndarraystores one fixed data type as contiguous memory, enabling fast, vectorized math with no manual loops.shape,ndim,size, anddtypeare the four attributes you’ll check constantly.- Basic slicing returns a view that shares memory with the original — use
.copy()when you need independence. - Boolean masking (
a[a > 0]) and fancy indexing (a[[0, 2, 4]]) are the two indexing tricks used everywhere. - Broadcasting lets you combine different shapes without loops — compare shapes from the right; dimensions must match, or one of them must be
1. - For interviews: know
argsort,cumsum,where,unique, andaxis=0vsaxis=1— they appear constantly in array-manipulation questions.