100 NumPy practice problems with solutions

Tired of watching NumPy tutorials and still freezing when it’s time to write your own array code? That frustration is completely normal — and it’s exactly what this post will help you overcome. We’ve gathered 100 NumPy practice problems with clear, step-by-step solutions to transform your theoretical understanding into hands-on confidence.

You’ll start with array creation, indexing, slicing, and reshaping, then progress to powerful tools like universal functions, broadcasting, linear algebra operations, random number generation, and practical data analysis tricks. Each problem is described in simple, everyday language — try solving it yourself first, and then check the solution to fully grasp the “why” behind every step. Why is this practice so vital? Because NumPy isn’t just a library; it’s the engine behind nearly every Python data project.

Every problem you solve strengthens your muscle memory, sharpens your intuition for efficient computation, and makes real data work feel accessible instead of intimidating. Whether you’re a beginner falling in love with data science or a job seeker preparing for technical interviews, these exercises will leave you feeling capable, excited, and genuinely ready.

Pick a challenge, open your Jupyter notebook, and feel that amazing “I can do this!” moment. Your journey to NumPy mastery starts now.

Also try it: 100 Python practice problems with solutions

1. Create a NumPy array from a list [1, 2, 3, 4, 5] and print it.

python

import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)

2. Create a 3×3 matrix of zeros using NumPy.

python

zeros = np.zeros((3, 3))
print(zeros)

3. Create a 2×4 matrix of ones.

python

ones = np.ones((2, 4))
print(ones)

4. Create a 2×2 identity matrix.

python

identity = np.eye(2)
print(identity)

5. Create a 4×4 matrix filled with a constant value, e.g., 7.

python

constant = np.full((4, 4), 7)
print(constant)

6. Create an array of 10 equally spaced numbers from 0 to 1 (inclusive).

python

lin = np.linspace(0, 1, 10)
print(lin)

7. Create an array of integers from 10 to 50 with step 5.

python

arr = np.arange(10, 51, 5)
print(arr)

8. Create a 3×3 matrix with random values between 0 and 1.

python

rand_mat = np.random.rand(3, 3)
print(rand_mat)

9. Create a 2×3 matrix of random integers between 1 and 100.

python

rand_int = np.random.randint(1, 101, size=(2, 3))
print(rand_int)

10. Find the shape, size, and data type of a given array.

python

arr = np.array([[1,2,3],[4,5,6]])
print("Shape:", arr.shape)
print("Size:", arr.size)
print("Dtype:", arr.dtype)

11. Reshape a 1D array of length 12 into a 3×4 matrix.

python

arr = np.arange(12)
reshaped = arr.reshape(3, 4)
print(reshaped)

12. Flatten a 2D array into a 1D array using ravel().

python

arr_2d = np.array([[1,2],[3,4]])
flat = arr_2d.ravel()
print(flat)

13. Transpose a 3×4 matrix.

python

mat = np.arange(12).reshape(3, 4)
transpose = mat.T
print(transpose)

14. Access the element at row 2, column 3 of a 3×3 matrix (0‑based indexing).

python

mat = np.arange(9).reshape(3, 3)
element = mat[2, 3]  # error: out of bounds? let's do valid: mat[1,2]
# Correct example:
mat = np.arange(9).reshape(3,3)
elem = mat[1,2]
print(elem)

15. Select the first two rows and last two columns of a 4×4 matrix.

python

mat = np.arange(16).reshape(4,4)
sub = mat[:2, -2:]
print(sub)

16. Extract all even numbers from a 1D array using boolean indexing.

python

arr = np.array([1,2,3,4,5,6,7,8,9])
evens = arr[arr % 2 == 0]
print(evens)

17. Replace all odd numbers in an array with -1.

python

arr = np.array([1,2,3,4,5])
arr[arr % 2 == 1] = -1
print(arr)

18. Add two arrays element-wise.

python

a = np.array([1,2,3])
b = np.array([4,5,6])
c = a + b
print(c)

19. Multiply two arrays element-wise.

python

c = a * b
print(c)

20. Compute the dot product of two 1D arrays.

python

dot = np.dot(a, b)
print(dot)

21. Compute the matrix multiplication of two 2D matrices.

python

A = np.array([[1,2],[3,4]])
B = np.array([[5,6],[7,8]])
C = A @ B  # or np.matmul(A, B)
print(C)

22. Compute the inverse of a square matrix.

python

A = np.array([[1,2],[3,4]])
A_inv = np.linalg.inv(A)
print(A_inv)

23. Compute the determinant of a 2×2 matrix.

python

det = np.linalg.det(A)
print(det)

24. Compute the eigenvalues and eigenvectors of a matrix.

python

eigvals, eigvecs = np.linalg.eig(A)
print("Eigenvalues:", eigvals)
print("Eigenvectors:", eigvecs)

25. Compute the sum of all elements in an array.

python

arr = np.array([1,2,3,4])
total = np.sum(arr)
print(total)

26. Compute the column‑wise sum of a 2D array.

python

mat = np.array([[1,2,3],[4,5,6]])
col_sum = np.sum(mat, axis=0)
print(col_sum)

27. Compute the row‑wise mean of a 2D array.

python

row_mean = np.mean(mat, axis=1)
print(row_mean)

28. Find the maximum value in a 2D array.

python

max_val = np.max(mat)
print(max_val)

29. Find the index of the maximum value along each column.

python

col_argmax = np.argmax(mat, axis=0)
print(col_argmax)

30. Concatenate two 1D arrays.

python

a = np.array([1,2])
b = np.array([3,4])
c = np.concatenate([a, b])
print(c)

31. Stack two 2D arrays vertically (row‑wise).

python

vstack = np.vstack((a.reshape(1,2), b.reshape(1,2))) # better with actual 2D
A = np.array([[1,2],[3,4]])
B = np.array([[5,6],[7,8]])
vert = np.vstack((A, B))
print(vert)

32. Stack two 2D arrays horizontally (column‑wise).

python

horiz = np.hstack((A, B))
print(horiz)

33. Split an array into 3 equal parts.

python

arr = np.arange(12)
split = np.split(arr, 3)
print(split)

34. Split an array at positions 2 and 5.

python

split_at = np.split(arr, [2,5])
print(split_at)

35. Create a copy of an array (deep copy) and show that modifying the copy does not affect the original.

python

original = np.array([1,2,3])
copy = original.copy()
copy[0] = 99
print("Original:", original)
print("Copy:", copy)

36. Create a view of an array (shallow copy) and demonstrate that changes affect the original.

python

view = original.view()
view[0] = 99
print("Original after view change:", original)

37. Use broadcasting to add a 1D array to each row of a 2D array.

python

mat = np.array([[1,2,3],[4,5,6]])
row = np.array([10,20,30])
result = mat + row
print(result)

38. Use broadcasting to multiply a scalar by a matrix.

python

mat = np.array([[1,2],[3,4]])
scaled = 3 * mat
print(scaled)

39. Compute the outer product of two vectors.

python

v1 = np.array([1,2,3])
v2 = np.array([4,5])
outer = np.outer(v1, v2)
print(outer)

40. Compute the inner product of two vectors.

python

inner = np.inner(v1, v1)  # or np.dot(v1, v1)
print(inner)

41. Compute the cross product of two 3D vectors.

python

v1 = np.array([1,0,0])
v2 = np.array([0,1,0])
cross = np.cross(v1, v2)
print(cross)

42. Compute the norm (Euclidean length) of a vector.

python

vec = np.array([3,4])
norm = np.linalg.norm(vec)
print(norm)

43. Normalize a vector (divide by its norm).

python

normalized = vec / np.linalg.norm(vec)
print(normalized)

44. Compute the covariance matrix of a 2D dataset (rows as variables).

python

data = np.array([[1,2,3],[4,5,6]])
cov = np.cov(data)
print(cov)

45. Compute the correlation coefficient matrix of a dataset.

python

corr = np.corrcoef(data)
print(corr)

46. Generate a random permutation of an array.

python

arr = np.array([1,2,3,4,5])
permuted = np.random.permutation(arr)
print(permuted)

47. Randomly shuffle an array in place.

python

np.random.shuffle(arr)
print(arr)

48. Seed the random generator for reproducibility (set seed 42).

python

np.random.seed(42)
rand_arr = np.random.rand(3)
print(rand_arr)

49. Create an array of 5 random numbers drawn from a standard normal distribution.

python

normal = np.random.randn(5)
print(normal)

50. Compute the sin of each element in an array.

python

angles = np.array([0, np.pi/2, np.pi])
sines = np.sin(angles)
print(sines)

51. Compute the exponential (e^x) of each element.

python

exp_arr = np.exp([0, 1, 2])
print(exp_arr)

52. Compute the natural logarithm of each element.

python

log_arr = np.log([1, np.e, np.e**2])
print(log_arr)

53. Compute the element‑wise square root of an array.

python

sqrt_arr = np.sqrt([1,4,9,16])
print(sqrt_arr)

54. Find the unique values in an array and their counts.

python

arr = np.array([1,2,2,3,3,3])
unique, counts = np.unique(arr, return_counts=True)
print("Values:", unique)
print("Counts:", counts)

55. Compute the cumulative sum (prefix sum) of an array.

python

cumsum = np.cumsum([1,2,3,4])
print(cumsum)

56. Compute the cumulative product of an array.

python

cumprod = np.cumprod([1,2,3,4])
print(cumprod)

57. Clip an array to values between 2 and 5.

python

arr = np.array([1,2,3,4,5,6])
clipped = np.clip(arr, 2, 5)
print(clipped)

58. Find the indices where a condition is true (e.g., values > 2).

python

indices = np.where(arr > 2)
print(indices)

59. Use np.where to replace values: keep original if condition true else 0.

python

replaced = np.where(arr > 2, arr, 0)
print(replaced)

60. Compute the dot product of two vectors using np.dot.

python

a = np.array([1,2])
b = np.array([3,4])
dot = np.dot(a, b)
print(dot)

61. Compute the Frobenius norm of a matrix.

python

mat = np.array([[1,2],[3,4]])
fro_norm = np.linalg.norm(mat, 'fro')
print(fro_norm)

62. Compute the trace (sum of diagonal) of a matrix.

python

trace = np.trace(mat)
print(trace)

63. Extract the diagonal of a matrix as a 1D array.

python

diag = np.diag(mat)
print(diag)

64. Create a diagonal matrix from a 1D array.

python

diag_mat = np.diag([1,2,3])
print(diag_mat)

65. Create a 5×5 matrix with 1’s on the border and 0’s inside.

python

border = np.ones((5,5))
border[1:-1, 1:-1] = 0
print(border)

66. Create a 5×5 matrix with 1’s on the anti‑diagonal (top‑right to bottom‑left).

python

anti = np.eye(5, k=0)[:, ::-1]
print(anti)

67. Create a checkerboard pattern 8×8 (alternating 0 and 1).

python

checker = np.indices((8,8)).sum(axis=0) % 2
# Alternatively: np.zeros((8,8), dtype=int); checker[1::2, ::2] = 1; checker[::2, 1::2] = 1
print(checker)

68. Find the most frequent value in an array (mode).

python

arr = np.array([1,1,2,2,2,3])
vals, counts = np.unique(arr, return_counts=True)
mode = vals[np.argmax(counts)]
print(mode)

69. Find the moving average of an array with window size 3 (simple).

python

def moving_avg(arr, w):
    return np.convolve(arr, np.ones(w)/w, mode='valid')
arr = np.array([1,2,3,4,5,6,7])
ma = moving_avg(arr, 3)
print(ma)

70. Compute the pairwise distance matrix between rows of a 2D array (Euclidean).

python

from scipy.spatial.distance import cdist
points = np.array([[0,0],[1,1],[2,2]])
dist = cdist(points, points)
print(dist)

71. Normalize a matrix by subtracting the mean and dividing by standard deviation (standardization).

python

data = np.array([[1,2,3],[4,5,6]])
mean = np.mean(data, axis=0)
std = np.std(data, axis=0)
normalized = (data - mean) / std
print(normalized)

72. Rescale a matrix to range [0,1] (min‑max scaling).

python

min_val = data.min()
max_val = data.max()
scaled = (data - min_val) / (max_val - min_val)
print(scaled)

73. Compute the histogram of an array with 5 bins.

python

hist, bin_edges = np.histogram(arr, bins=5)
print("Histogram:", hist)
print("Bin edges:", bin_edges)

74. Compute the mean and variance of an array, ignoring NaN values.

python

arr_with_nan = np.array([1,2,np.nan,4])
mean = np.nanmean(arr_with_nan)
var = np.nanvar(arr_with_nan)
print(mean, var)

75. Use np.polyfit to fit a line to points (x,y) and predict y at x=5.

python

x = np.array([0,1,2,3,4])
y = np.array([1,3,5,7,9])
coeff = np.polyfit(x, y, 1)  # slope, intercept
y_pred = np.polyval(coeff, 5)
print(y_pred)

76. Generate a 1D array of 20 random integers from 0 to 10 and compute the median.

python

rand_ints = np.random.randint(0, 11, 20)
median = np.median(rand_ints)
print(median)

77. Find the index of the maximum absolute value in an array.

python

arr = np.array([-10, -5, 0, 5, 10])
idx = np.argmax(np.abs(arr))
print(idx)

78. Compute the element‑wise absolute value of an array.

python

abs_arr = np.abs(arr)
print(abs_arr)

79. Create a 1D array of 10 numbers and convert it to a list of Python floats.

python

arr = np.random.rand(10)
lst = arr.tolist()
print(lst)

80. Use np.fromfunction to create a 5×5 matrix where each element is i*j.

python

mat = np.fromfunction(lambda i, j: i * j, (5,5), dtype=int)
print(mat)

Also try it: 100 Pandas practice problems with solutions

81. Use np.where to set values greater than 0.5 to 1 and less than 0.5 to 0 (threshold).

python

arr = np.random.rand(10)
binary = np.where(arr > 0.5, 1, 0)
print(binary)

82. Compute the element‑wise remainder of division by 2 (i.e., mod 2).

python

remainder = arr % 2
print(remainder)

83. Compute the element‑wise floor of an array.

python

floored = np.floor(arr)
print(floored)

84. Compute the element‑wise ceil of an array.

python

ceiled = np.ceil(arr)
print(ceiled)

85. Use np.linspace to create 5 points between 0 and 10 inclusive.

python

points = np.linspace(0, 10, 5)
print(points)

86. Use np.logspace to create 5 points logarithmically spaced between 1 and 1000.

python

logsp = np.logspace(0, 3, 5, base=10)  # 10^0 = 1 to 10^3 = 1000
print(logsp)

87. Compute the row‑wise variance of a 2D array.

python

row_var = np.var(mat, axis=1)
print(row_var)

88. Compute the column‑wise standard deviation of a 2D array.

python

col_std = np.std(mat, axis=0)
print(col_std)

89. Use np.loadtxt to read a CSV file with comma delimiter (create a dummy file).

python

# Assume file.csv exists
data = np.loadtxt('file.csv', delimiter=',')
print(data)

90. Use np.savetxt to save an array to a CSV file.

python

arr = np.array([[1,2,3],[4,5,6]])
np.savetxt('out.csv', arr, delimiter=',')

91. Compare two arrays element‑wise and return a boolean array (element equal).

python

a = np.array([1,2,3])
b = np.array([1,4,3])
eq = a == b
print(eq)

92. Use np.isclose to compare two floating‑point arrays with tolerance.

python

c = np.array([0.1+0.2, 0.3])
d = np.array([0.3, 0.3])
close = np.isclose(c, d)
print(close)

93. Use np.eye to create a 1D array of ones (not possible; use np.ones).

python

ones = np.ones(5)
print(ones)

94. Use np.tile to repeat a 2D array 2 times vertically and 3 times horizontally.

python

small = np.array([[1,2],[3,4]])
tiled = np.tile(small, (2,3))
print(tiled)

95. Use np.repeat to repeat each element of a 1D array twice.

python

arr = np.array([1,2,3])
repeated = np.repeat(arr, 2)
print(repeated)

96. Compute the integral of a function using np.trapz (trapezoidal rule).

python

x = np.linspace(0, np.pi, 100)
y = np.sin(x)
integral = np.trapz(y, x)
print(integral)  # approx 2

97. Use np.diff to compute the first difference of an array.

python

arr = np.array([1,3,6,10])
diff = np.diff(arr)
print(diff)  # [2,3,4]

98. Use np.gradient to compute the gradient of a function.

python

y = np.array([1,2,4,7,11])
grad = np.gradient(y)
print(grad)  # approximate derivative

99. Use np.argsort to get the indices that sort an array.

python

arr = np.array([3,1,2])
idx = np.argsort(arr)
print(idx)  # [1,2,0]

100. Use np.percentile to compute the 25th, 50th, and 75th percentiles.

python

data = np.random.randn(1000)
perc = np.percentile(data, [25,50,75])
print(perc)

Final Thought

You’ve arrived — not with a loud bang, but with a quiet steadiness. One hundred NumPy problems, each one a small breath of practice, have settled into your fingers and your mind. Arrays have been created, sliced, broadcast, and transformed, and through it all, something deeper has grown: a calm, unshakable confidence that doesn’t rush but simply knows.

There’s a gentle power in realizing that the numerical world is no longer intimidating. Linear algebra feels less like a storm and more like a still lake you can now navigate. Every universal function, every reshape, every random seed you planted has quietly built a garden of skill inside you.

Let this practice stay with you like a peaceful hum beneath your daily work. Return to these problems whenever the noise of confusion creeps in. The beauty of NumPy — and of learning itself — is that it’s always there, patient and steady, waiting for you to take the next small step. Rest a moment, smile at how far you’ve come, and carry that serenity with you into every dataset you meet.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top