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:

  1. NumPy stands for Numerical Python.
  2. It is a third-party library — you install it with pip install numpy before using it.
  3. Its main feature is the ndarray (n-dimensional array) — a fast, memory-efficient, multi-dimensional array.
  4. Unlike a Python list, a NumPy array stores only one data type, as raw contiguous memory — this is what makes it so fast.
  5. NumPy lets you do math on an entire array at once, without writing a manual loop — this is called vectorization.
  6. Almost every major Python data-science and machine-learning library (pandas, scikit-learn, PyTorch) is built on top of NumPy.
what_is_numpy.py

2. Why is NumPy Faster Than a Python List?

why_numpy_is_fast.py

3. Key Attributes of an Array

Attributes you will use constantly
attributemeaning
shapeA tuple showing the size of each dimension, e.g. (3, 4)
ndimHow many dimensions the array has (1 = a list, 2 = a table, ...)
sizeThe total number of elements in the array
dtypeThe data type of every element, e.g. int64, float64
itemsizeHow many bytes each element uses
TThe transposed version of the array (rows and columns swapped)
attributes_example.py
shape = (2, 3) → 2 rows, 3 columns123456← row 0← row 1

4. Creating Arrays — Every Way, One by One

4.1 np.array() — From a Python List

np_array.py

4.2 np.zeros() — An Array Full of Zeros

np_zeros.py

4.3 np.ones() — An Array Full of Ones

np_ones.py

4.4 np.full() — An Array Filled With a Chosen Value

np_full.py

4.5 np.eye() — An Identity Matrix

np_eye.py

4.6 np.arange() — Like Python’s range(), but Returns an Array

np_arange.py

4.7 np.linspace() — Evenly Spaced Numbers

np_linspace.py

4.8 np.random.rand() and np.random.randint() — Random Arrays

np_random.py

4.9 np.zeros_like() — Same Shape as Another Array

np_zeros_like.py

5. Indexing and Slicing

5.1 Basic Indexing (1-D Array)

indexing_1d.py

5.2 Indexing a 2-D Array (Matrix)

indexing_2d.py

5.3 Boolean Masking — Picking Items by Condition

Points:

  1. You can compare a whole array to a value — this gives back an array of True/False.
  2. You can then use that True/False array to filter the original array.
  3. This is one of the most useful NumPy tricks, used constantly in real code and interviews.
boolean_masking.py

5.4 Fancy Indexing — Picking Multiple Specific Positions

fancy_indexing.py

6. Views vs Copies — An Important Beginner Trap

Points:

  1. Basic slicing (a[1:3]) gives you a view — it shares the same memory as the original array.
  2. Changing a view also changes the original array!
  3. Use .copy() when you need a completely independent array.
view_problem.py
copy_solution.py

7. Reshaping and Combining Arrays

7.1 reshape() — Change the Shape Without Changing the Data

reshape_example.py

7.2 flatten() vs ravel() — Back to 1-D

flatten_ravel.py

7.3 T — Transpose (Swap Rows and Columns)

transpose_example.py

7.4 np.concatenate(), np.vstack(), np.hstack() — Combining Arrays

combining_arrays.py

8. Vectorized Math — The Whole Point of NumPy

Points:

  1. “Vectorized” means you can apply an operation to every element at once, with no explicit loop.
  2. This is both shorter to write and much faster to run than a Python for loop.
vectorized_math.py

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):

  1. Compare the shapes of the two arrays, starting from the right side.
  2. Two dimensions are compatible if they are equal, or if one of them is 1.
  3. NumPy “stretches” the smaller dimension to match — without actually copying data in memory.
matrix (3x3) + row (shape 3,) → row is repeated for every line123456+102030row (used on EVERY row)
broadcasting_row.py
broadcasting_column.py

10. Every Common Method — Explained One by One

10.1 np.sort() / a.sort() — Sorting

sort_numpy.py

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.

argsort_example.py

10.3 sum(), mean(), std(), var()

statistics_methods.py

10.4 min(), max(), argmin(), argmax()

min_max_methods.py

10.5 np.unique() — Unique Values, Sorted

unique_example.py

10.6 np.where() — Conditional Selection

where_example.py

10.7 cumsum() — Running (Cumulative) Sum

cumsum_example.py

10.8 any() and all()

any_all_example.py

10.9 astype() — Convert to a Different Data Type

astype_example.py

10.10 sum(axis=...) — Summing Along Rows or Columns

Points:

  1. For 2-D arrays, axis=0 means “go down the columns.”
  2. axis=1 means “go across the rows.”
  3. This confuses almost every beginner at first — the diagram below should help.
123456↓ axis=0 (down columns)→ axis=1 (across rows)
axis_example.py

11. All Methods in One Table (Quick Reference)

The NumPy methods you will use most often
methodwhat 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
TTranspose (swap rows/columns)

12. A Worked Example Combining Several Concepts

worked_example.py

13. Interview Patterns (Question First, Then Solution)

13.1 Pattern: Check if an Array is Sorted (Vectorized)

❓ Interview Question:

  1. Problem: Given a NumPy array, check whether it is sorted in ascending order — without writing a manual loop.
  2. Example:
    • Input: [1, 2, 2, 5]
    • Expected Output: True
    • Input: [1, 5, 2]
    • Expected Output: False
  3. Hint: Compare the array to a “shifted” version of itself.

✅ Approach:

  1. Compare every item (except the last) to the item right after it.
  2. If every item is less than or equal to its neighbor, the array is sorted.
  3. np.all() checks that this is true for the entire array at once.
is_sorted_numpy.py

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:

  1. 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.”
  2. Example:
    • Input: nums = [1, 2, 3, 4, 5], target = 3
    • Expected Output: values greater than target → [4, 5]
  3. Hint: Boolean masking turns a filtering problem into one line.

✅ Approach:

  1. Build a boolean mask comparing the whole array to the target at once.
  2. Use that mask to select only the matching values.
filter_greater_than_target.py

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:

  1. Problem: Given a 2-D matrix, find the sum of each row and the sum of each column.
  2. Example:
    • Input: [[1, 2, 3], [4, 5, 6]]
    • Expected Output: row sums [6, 15], column sums [5, 7, 9]
  3. Hint: This is exactly what the axis parameter is for.

✅ Approach:

  1. axis=1 sums across each row.
  2. axis=0 sums down each column.
row_col_sums.py

Complexity: Time = O(rows × columns), Space = O(rows + columns).

14. NumPy vs list vs array — When to Use Which

Decision guide
situationbest choice
Small, mixed-type collection, general logiclist
Need O(1) push/pop from both endscollections.deque
Large numeric dataset, need fast mathnumpy.ndarray
Need multi-dimensional arrays / matrix mathnumpy.ndarray
Compact single-type binary buffer onlyarray.array

15. Practice Problems (Try These Yourself)

  1. Given an array of exam scores, find how many students scored above the average.
  2. Write a function that reverses each row of a 2-D matrix.
  3. Given two arrays of the same shape, compute the elementwise maximum.
  4. Find the index of the closest value to a target number in an array.
  5. Compute the moving average of a 1-D array with a given window size.

16. Key Takeaways

  1. numpy.ndarray stores one fixed data type, contiguously in memory — this is what makes it fast.
  2. Vectorized operations (a + b, a ** 2, np.sum(a)) replace manual loops and run much faster.
  3. Basic slicing returns a view, not a copy — use .copy() when you need independence.
  4. Boolean masking (a[a > 0]) and fancy indexing (a[[0, 2, 4]]) are the two most useful indexing tricks.
  5. Broadcasting lets you combine arrays of different shapes without writing loops, following the “match or 1” rule.
  6. axis=0 means down the columns, axis=1 means across the rows — a common beginner confusion worth memorizing.
  7. argsort, cumsum, where, and unique show up constantly in interview questions about arrays.

10. Every Important Method — Explained One by One

10.1 np.sort() — Sort the Array

np_sort.py

10.2 argsort() — Get the Indexes That Would Sort the Array

This one confuses beginners — here is the difference from sort():

  1. sort() gives you the sorted values.
  2. argsort() gives you the indexes that would put the array in sorted order.
argsort_example.py

10.3 sum(), mean(), std(), var()

statistics_methods.py

10.4 min(), max(), argmin(), argmax()

min_max_methods.py

10.5 np.unique() — Get Unique Values, Sorted

unique_example.py

10.6 np.where() — Choose a Value Based on a Condition

where_example.py

10.7 cumsum() — Running (Cumulative) Total

cumsum_example.py

10.8 any() and all()

any_all_example.py

10.9 astype() — Convert to a Different Data Type

astype_example.py

10.10 sum(axis=...) — Summing Along Rows or Columns

This trips up a lot of beginners with 2-D arrays:

  1. axis=0 means “go down the columns” — sum each column.
  2. axis=1 means “go across the rows” — sum each row.
axis_example.py

11. All Methods in One Table (Quick Reference)

High-frequency ndarray methods and functions
methodwhat 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:

  1. Problem: Given an array of numbers, rescale every value into the range 0 to 1.
  2. Example:
    • Input: [65, 90, 72, 88, 55]
    • Expected Output: values between 0.0 and 1.0, where the smallest input becomes 0.0 and the largest becomes 1.0.
  3. Hint: Subtract the minimum, then divide by the range (max - min).

✅ Approach:

  1. Find the minimum and maximum values of the array.
  2. For every value: subtract the minimum (shifts the range to start at 0).
  3. Divide by (max - min) (scales the range down to fit between 0 and 1).
normalize.py

Complexity: Time = O(n), Space = O(n) for the result array.

12.2 Pattern: Distance Between Two Points

❓ Interview Question:

  1. Problem: Given two points as arrays (e.g. [x, y]), calculate the straight-line (Euclidean) distance between them.
  2. Example:
    • Input: p1 = [0, 0], p2 = [3, 4]
    • Expected Output: 5.0
  3. Hint: This is the same formula as the Pythagorean theorem: square the differences, add them, take the square root.

✅ Approach:

  1. Subtract the two points to get the difference in each dimension.
  2. Square every difference.
  3. Add the squares together, then take the square root of the total.
euclidean_distance.py

Complexity: Time = O(d) where d = number of dimensions, Space = O(1).

12.3 Pattern: Check if an Array is Sorted (Vectorized)

❓ Interview Question:

  1. Problem: Given an array, check whether it is sorted in ascending order — without writing a manual loop.
  2. Example:
    • Input: [1, 2, 2, 5]
    • Expected Output: True
    • Input: [1, 5, 2]
    • Expected Output: False
  3. Hint: Compare the array to a “shifted” version of itself.

✅ Approach:

  1. Compare every element (except the last) to the element right after it.
  2. If every one of those comparisons is True (each item is less-than-or-equal to the next), the array is sorted.
  3. np.all() checks that every comparison passed.
is_sorted_vectorized.py

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:

  1. Problem: Given an array of numbers and a target sum, find all pairs of numbers that add up to the target.
  2. Example:
    • Input: nums = [2, 7, 11, 15, -2], target = 9
    • Expected Output: [(2, 7)]
  3. Hint: For each number, check whether target - number has already been seen.

✅ Approach:

  1. Keep a set of numbers seen so far.
  2. For each number, calculate what its “partner” would need to be (target - number).
  3. If that partner is already in the seen set, you found a pair.
  4. Add the current number to the seen set, then move on.
two_sum_pairs.py

Complexity: Time = O(n), Space = O(n) for the seen set.

13. Practice Problems (Try These Yourself)

  1. Given a 2-D array, find the sum of its diagonal elements.
  2. Given an array of temperatures, count how many days were above the average.
  3. Given two arrays of the same shape, compute their element-wise product (not the dot product).
  4. Reverse a 2-D array both horizontally and vertically.
  5. 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

Decision guide
situationbest choice
Small, mixed-type collection, general logiclist
Need O(1) push/pop from both endscollections.deque
Large numeric dataset, need math (sum, mean, matrix ops)numpy.ndarray
Need multi-dimensional arrays / linear algebranumpy.ndarray
Compact single-type binary buffer, no numeric operationsarray.array

15. Key Takeaways

  1. numpy.ndarray stores one fixed data type as contiguous memory, enabling fast, vectorized math with no manual loops.
  2. shape, ndim, size, and dtype are the four attributes you’ll check constantly.
  3. Basic slicing returns a view that shares memory with the original — use .copy() when you need independence.
  4. Boolean masking (a[a > 0]) and fancy indexing (a[[0, 2, 4]]) are the two indexing tricks used everywhere.
  5. Broadcasting lets you combine different shapes without loops — compare shapes from the right; dimensions must match, or one of them must be 1.
  6. For interviews: know argsort, cumsum, where, unique, and axis=0 vs axis=1 — they appear constantly in array-manipulation questions.