PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
  • Quizzes
  • Code Editor
Home » Python Exercises » Python NumPy Exercise: 50 Questions With Solutions (Beginner to Advanced)

Python NumPy Exercise: 50 Questions With Solutions (Beginner to Advanced)

Updated on: August 31, 2025 | 32 Comments

NumPy, short for Numerical Python, is a fundamental library for data science. It’s used to create and manipulate multidimensional arrays, making it incredibly useful for numerical operations and data analysis.

This article gives you 50 NumPy coding practice problems with solution starting from fundamentals to linear algebra each with a hint, solution, and short explanation so you learn by doing, not just reading.

Below topics are covered in this exercise

  • Basics: imports, creation routines, identity matrices, versioning
  • Intermediate: Array manipulation and common operations
  • Indexing & Slicing: rows, columns, sub-arrays, boolean masks
  • Array Operations: element-wise math, dot product, normalization, stats
  • Random Numbers: random floats/ints, shuffling, sorting
  • Reshaping & Stacking: reshape, flatten, split, tile vs repeat
  • Boolean & Filtering: conditional filtering, replace, unique counts, set ops
  • Advanced: diagonals, eigenvalues/vectors, solve, inversion, structured arrays

How to use this guide

  1. Try the question first.
  2. Peek at the hint only if needed.
  3. Write your own solution, then compare with the provided code.
  4. Read the explanation and tweak inputs (shapes, dtypes) to deepen understanding.

Prerequisites

  • Python 3.x
  • NumPy installed: pip install numpy

Use Online Code Editor to solve the exercise.

+ Table of Content (50 Exercises)

Table of contents

  • Exercise 1: Create a 1D NumPy array of numbers from 0 to 9
  • Exercise 2: Convert 1D array to 2D
  • Exercise 3: Print Array Attributes
  • Exercise 4: Create a 3×3 NumPy array of all True
  • Exercise 5: Extract the documentation of NumPy’s arange() function
  • Exercise 6: Create a 1D array filled with zeros and another filled with ones
  • Exercise 7: Create a 1D array of 10 evenly spaced values between 5 and 50
  • Exercise 8: Convert a Python list into a NumPy array
  • Exercise 9: Find the memory size of a NumPy array of numbers from 0 to 9
  • Exercise 10: Reverse a 1D NumPy array
  • Exercise 11: Create a 3×3 identity matrix
  • Exercise 12: Create a 4×4 array and extract its first row and last column
  • Exercise 13: Extract Odd Rows and Even Columns
  • Exercise 14: Stack arrays horizontally
  • Exercise 15: Slice the first two rows and first two columns from a 4×4 array
  • Exercise 16: Replace all odd numbers in a NumPy array with -1
  • Exercise 17: Get the indices of non-zero elements in an array
  • Exercise 18: Find the common items between two arrays
  • Exercise 19: Perform arithmetic operations on two NumPy arrays element-wise
  • Exercise 20: Matrix multiplication
  • Exercise 21: Compute the mean, median, and standard deviation of a NumPy array
  • Exercise 22: Remove common items from array
  • Exercise 23: Normalize a NumPy array (values between 0 and 1)
  • Exercise 24: Get the positions where elements of array a and b match
  • Exercise 25: Extract numbers from an array
  • Exercise 26: Create a random 3×2 matrix and find its maximum and minimum values
  • Exercise 27: Sorting a NumPy array based on a specific column
  • Exercise 28: Delete and Insert a Column in a NumPy Array
  • Exercise 29: Swap column 1 and 2 in a 2D array
  • Exercise 30: Generate 10 random integers between 1 and 100
  • Exercise 31: Create a 3×3 array of random integers and sort it row-wise
  • Exercise 32: Shuffle an array randomly
  • Exercise 33: Create a 5×5 2D array with 1s on the border and 0s inside.
  • Exercise 34: Check if an array contains any NaN values.
  • Exercise 35: Sort the rows of a 2D array based on the values of the second column
  • Exercise 36: Flatten a multi-dimensional NumPy array
  • Exercise 37: Stack two arrays vertically and horizontally
  • Exercise 38: Split an array into 3 equal parts
  • Exercise 39: Perform Addition and Squaring on Arrays
  • Exercise 40: Invert a matrix
  • Exercise 41: Use boolean indexing to filter values less than a given number
  • Exercise 42: Count the number of occurrences of each unique element
  • Exercise 43: Find the intersection and union of two arrays
  • Exercise 44: Transpose a matrix
  • Exercise 45: Compute the eigenvalues and eigenvectors of a matrix
  • Exercise 46: Solve a linear equation
  • Exercise 47: Create an 8×8 checkerboard pattern using 0s and 1s
  • Exercise 48: Find nearest value
  • Exercise 49: Convert to object array
  • Exercise 50: Compute the mean, median, and standard deviation of a NumPy array

Exercise 1: Create a 1D NumPy array of numbers from 0 to 9

Expected Output:

[0 1 2 3 4 5 6 7 8 9]
+ Hint

Use the np.arange() function.

+ Show Solution
import numpy as np

arr = np.arange(10)
print(arr)Code language: Python (python)

Explanation: np.arange(10) generates values from 0 to 9. The default step is 1.

Exercise 2: Convert 1D array to 2D

Write a code to convert a 1D array to a 2D array with 2 rows.

Given:

import numpy as np
arr = np.arange(6)Code language: Python (python)

Expected Output:

Original Array: [0 1 2 3 4 5]
Reshaped 2x3 Array:
[[0 1 2]
[3 4 5]]
+ Hint

Use reshape(rows, cols) function.

+ Show Solution
import numpy as np

arr = np.arange(6)
arr_2d = arr.reshape(2, 3)
print(arr_2d)Code language: Python (python)

Explanation: The .reshape() method is used to give a new shape to an array without changing its data. We specify the new shape as a tuple (rows, columns). Since we want 2 rows and the original array has 6 elements, the new array must have 5 columns (2 * 3 = 6).

Exercise 3: Print Array Attributes

Instructions: Print the following attributes of the array:

  • The shape of the array.
  • The number of array dimensions.
  • The size of each element in bytes.

Given:

import numpy as np
my_array = np.array([[1, 2], [3, 4], [5, 6], [7, 8]], dtype=np.uint16)Code language: Python (python)

Expected Output:

The shape of the array is: (4, 2)
The number of dimensions is: 2
The size of each element in bytes is: 2
+ Show Solution
import numpy as np

# Create the 4x2 array of type unsigned int16
# We use np.array() and specify the dtype
my_array = np.array([[1, 2], [3, 4], [5, 6], [7, 8]], dtype=np.uint16)

# Print the attributes
print("The shape of the array is:", my_array.shape)
print("The number of dimensions is:", my_array.ndim)
print("The size of each element in bytes is:", my_array.itemsize)Code language: Python (python)

Explanation: np.array() converts a Python list into a NumPy array. This allows efficient mathematical operations.

Exercise 4: Create a 3×3 NumPy array of all True

Expected Output:

[[ True  True  True]
[ True True True]
[ True True True]]
+ Hint

Use np.ones() with dtype=bool.

+ Show Solution
import numpy as np

arr = np.ones((3, 3), dtype=bool)
print(arr)Code language: Python (python)

Explanation: The np.full() function is a powerful way to create an array of any given shape filled with a specific value. The first argument (3, 3) specifies the shape (3 rows, 3 columns), and the second argument True is the value to fill the array with. The dtype=bool ensures that the array’s data type is boolean.

Exercise 5: Extract the documentation of NumPy’s arange() function

Expected Output:

arange([start,] stop[, step,], dtype=None, *, like=None)
............
+ Hint

Use Python’s np.info() method

+ Show Solution
import numpy as np

np.info(np.arange)Code language: Python (python)

Explanation: np.info() displays the docstring of a function. It helps understand usage, parameters, and return type.

Exercise 6: Create a 1D array filled with zeros and another filled with ones

Expected Output:

Zeros: [0. 0. 0. 0. 0.]
Ones: [1. 1. 1. 1. 1.]
+ Hint

Use np.zeros() and np.ones().

+ Show Solution
import numpy as np

zeros_arr = np.zeros(5)
ones_arr = np.ones(5)

print("Zeros:", zeros_arr)
print("Ones:", ones_arr)Code language: Python (python)

Explanation:

  • np.ones(5) → Creates [1. 1. 1. 1. 1.]
  • np.zeros(5) → Creates [0. 0. 0. 0. 0.]

Exercise 7: Create a 1D array of 10 evenly spaced values between 5 and 50

Expected Output:

[ 5. 10. 15. 20. 25. 30. 35. 40. 45. 50.]
+ Hint

Use np.linspace(start, stop, num).

+ Show Solution
import numpy as np

arr = np.linspace(5, 50, 10)
print(arr)Code language: Python (python)

Explanation: np.linspace(5, 50, 10) generates 10 evenly spaced numbers starting from 5 to 50 (inclusive).

Exercise 8: Convert a Python list into a NumPy array

Given:

py_list = [1, 2, 3, 4, 5]Code language: Python (python)
+ Hint

Use np.array(list).

+ Show Solution
import numpy as np

py_list = [1, 2, 3, 4, 5]
arr = np.array(py_list)
print(arr)Code language: Python (python)

Explanation: np.array() converts a Python list into a NumPy array. This allows efficient mathematical operations.

Exercise 9: Find the memory size of a NumPy array of numbers from 0 to 9

Expected Output:

Array: [0 1 2 3 4 5 6 7 8 9]
Memory size in bytes: 80
+ Hint

Use nbytes attribute

+ Show Solution
import numpy as np

arr = np.arange(10)
print("Array:", arr)
print("Memory size in bytes:", arr.nbytes)Code language: Python (python)

Explanation: Each element in NumPy has a fixed size. nbytes gives the total memory used by the array

Exercise 10: Reverse a 1D NumPy array

Given:

import numpy as np
arr = np.arange(10)Code language: Python (python)

Expected Output:

[9 8 7 6 5 4 3 2 1 0]
+ Hint

Use slicing [::-1].

+ Show Solution
import numpy as np

arr = np.arange(10)
reversed_arr = arr[::-1]
print(reversed_arr)Code language: Python (python)

Explanation: The slice [::-1] steps backwards, effectively reversing the array.

Exercise 11: Create a 3×3 identity matrix

Use tuple unpacking to swap the values of two variables without using a temporary variable.

Expected Output:

[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
+ Hint

Use np.eye() function.

+ Show Solution
import numpy as np

identity = np.eye(3)
print(identity)Code language: Python (python)

Explanation: An identity matrix has 1s on the diagonal and 0s elsewhere. The np.eye(3) creates a 3×3 identity matrix.

Exercise 12: Create a 4×4 array and extract its first row and last column

Expected Output:

Array:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]
[13 14 15 16]]
First Row: [1 2 3 4]
Last Column: [ 4 8 12 16]
+ Hint
  • Use array indexing [0] for the first row.
  • Use slicing [:, -1] to get last column.
+ Show Solution
import numpy as np

arr = np.arange(1, 17).reshape(4, 4)
print("Array:\n", arr)

first_row = arr[0]
print("First Row:", first_row)

last_col = arr[:, -1]
print("Last Column:", last_col)Code language: Python (python)

Explanation:

  1. np.arange(1, 10).reshape(3, 3) creates a 3×3 array with numbers 1–9.
  2. arr[0] selects the first row (indexing starts at 0).

Exercise 13: Extract Odd Rows and Even Columns

Extract an array of odd rows and even columns from below NumPy array.

Problem Breakdown

  • Rows: In programming, indexing starts at 0. Odd-indexed rows would be rows 1 and 3.
  • Columns: Even-indexed columns would be columns 0 and 2.

Given:

import numpy as np
sampleArray = np.array([
    [3, 6, 9, 12], 
    [15, 18, 21, 24], 
    [27, 30, 33, 36], 
    [39, 42, 45, 48], 
    [51, 54, 57, 60]
])Code language: Python (python)

Expected Output:

New Array with Odd Rows and Even Columns:
[[15 21]
[39 45]]
+ Hint

Use np.hstack().

+ Show Solution
import numpy as np

# Original array
sampleArray = np.array([
    [3, 6, 9, 12], 
    [15, 18, 21, 24], 
    [27, 30, 33, 36], 
    [39, 42, 45, 48], 
    [51, 54, 57, 60]
])

# Use slicing to select odd rows and even columns
# The slice [1::2] selects every second element starting from index 1 (odd rows).
# The slice [::2] selects every second element starting from index 0 (even columns).
newArray = sampleArray[1::2, ::2]

print("Original Array:")
print(sampleArray)

print("\nNew Array with Odd Rows and Even Columns:")
print(newArray)Code language: Python (python)

Explanation:

The syntax array[start:stop:step] lets you specify which elements to select.

1::2 for the rows means:

  • Start: at index 1 (the second row).
  • Stop: Omitted, so it goes to the end of the array.
  • Step: 2, meaning it selects every second row. This gives us rows at indices 1 and 3.

::2 for the columns means:

  • Start: Omitted, so it defaults to 0 (the first column).
  • Stop: Omitted, so it goes to the end.
  • Step: 2, meaning it selects every second column. This gives us columns at indices 0 and 2.

By combining these two slices, sampleArray[1::2, ::2], NumPy efficiently creates a new array containing the elements at the intersection of the specified rows and columns.

Exercise 14: Stack arrays horizontally

Given:

import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])Code language: Python (python)

Expected Output:

[1 2 3 4 5 6]
+ Hint

Use np.hstack().

+ Show Solution
import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
stacked_arr = np.hstack((a, b))
print(stacked_arr)Code language: Python (python)

Explanation: The np.hstack() function stands for “horizontal stack.” It stacks arrays in sequence column-wise, effectively concatenating them along the second axis. For 1D arrays, this simply joins them end-to-end.

Exercise 15: Slice the first two rows and first two columns from a 4×4 array

Write a code to Create a 4×4 NumPy array and extract the first two rows and first two columns.

Expected Output:

Array:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]
[13 14 15 16]]
First 2 rows and columns:
[[1 2]
[5 6]]
+ Hint

Use slicing [0:2, 0:2].

+ Show Solution
import numpy as np

arr = np.arange(1, 17).reshape(4, 4)
print("Array:\n", arr)

sub_arr = arr[0:2, 0:2]
print("First 2 rows and columns:\n", sub_arr)Code language: Python (python)

Explanation:

  • arr[0:2, 0:2] → selects rows 0–1 and columns 0–1.
  • The result is a 2×2 sub-matrix.

Exercise 16: Replace all odd numbers in a NumPy array with -1

Expected Output:

Original Array: [ 1  2  3  4  5  6  7  8  9 10]
Modified Array: [-1 2 -1 4 -1 6 -1 8 -1 10]
+ Hint

Use boolean indexing with modulo % to find odd numbers.

+ Show Solution
import numpy as np

arr = np.arange(1, 11)
print("Original Array:", arr)

arr[arr % 2 == 1] = -1
print("Modified Array:", arr)Code language: Python (python)

Explanation:

  • arr % 2 == 1 → creates a boolean mask for odd numbers.
  • Assigning -1 replaces all odd values.

Exercise 17: Get the indices of non-zero elements in an array

Given:

import numpy as np
arr = np.array([1, 0, 2, 0, 3, 0, 4])Code language: Python (python)

Expected Output:

Array: [1 0 2 0 3 0 4]
Indices: (array([0, 2, 4, 6]),)
+ Hint

Use np.nonzero().

+ Show Solution
import numpy as np

arr = np.array([1, 0, 2, 0, 3, 0, 4])
print("Array:", arr)

indices = np.nonzero(arr)
print("Indices of non-zero elements:", indices)Code language: Python (python)

Explanation:

  • np.nonzero(arr) returns a tuple of indices where elements are non-zero.
  • In this example → (array([0, 2, 4, 6]),) meaning non-zero elements are at positions 0, 2, 4, 6.

Exercise 18: Find the common items between two arrays

Given:

import numpy as np

a = np.array([1, 2, 3, 2, 8, 4, 2, 4])
b = np.array([2, 4, 5, 6, 8])Code language: Python (python)

Expected Output:

[2 4 8]
+ Hint

Use the np.intersect1d() function

+ Show Solution
import numpy as np

a = np.array([1, 2, 3, 2, 8, 4, 2, 4])
b = np.array([2, 4, 5, 6, 8])
common_items = np.intersect1d(a, b)
print(common_items)Code language: Python (python)

Explanation: The np.intersect1d() function finds the unique common elements between two arrays and returns them in a sorted 1D array. This is a highly efficient way to perform set-like operations on NumPy arrays.

Exercise 19: Perform arithmetic operations on two NumPy arrays element-wise

  • Add two NumPy arrays element by element.
  • Multiply two NumPy arrays element by element.

Given:

import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])Code language: Python (python)

Expected Output:

Element-wise Sum: [5 7 9]
Element-wise multiplication: [ 4 10 18]
+ Hint
  • Use the + operator or np.add().
  • Use the * operator or np.multiply().
+ Show Solution
import numpy as np

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

add = a + b   # or np.add(a, b)
print("Element-wise Sum:", add)

product = a * b   # or np.multiply(a, b)
print("Element-wise multiplication:", product)Code language: Python (python)

Exercise 20: Matrix multiplication

Write a code to compute the dot product of two NumPy arrays

Given:

import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])Code language: Python (python)

Expected Output:

Dot Product: 32
+ Hint

Use np.dot() or @ operator.

+ Show Solution
import numpy as np

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

dot_product = np.dot(a, b)   # or a @ b
print("Dot Product:", dot_product)Code language: Python (python)

Explanation:

For matrix multiplication, it’s crucial to distinguish it from element-wise multiplication (*). The @ operator and the np.dot() function are specifically designed for matrix multiplication, following the rules of linear algebra. The result is a new matrix where the value at each position is the dot product of a row from the first matrix and a column from the second.

The dot product is calculated as: 1*4 + 2*5 + 3*6 = 32.

Exercise 21: Compute the mean, median, and standard deviation of a NumPy array

  • Mean: Average of numbers.
  • Median: Middle value when sorted.
  • Standard Deviation: How spread out values are from the mean.

Given:

import numpy as np
arr = np.array([10, 20, 30, 100, 200, 300])Code language: Python (python)

Expected Output:

Mean: 110.0
Median: 65.0
Standard Deviation: 107.08252269472673
+ Hint

Use np.mean(), np.median(), np.std().

+ Show Solution
import numpy as np

arr = np.array([10, 20, 30, 40, 50])

print("Mean:", np.mean(arr))
print("Median:", np.median(arr))
print("Standard Deviation:", np.std(arr))Code language: Python (python)

Exercise 22: Remove common items from array

Given:

import numpy as np

a = np.array([1, 2, 3, 4, 5])
b = np.array([5, 6, 7, 8, 9])Code language: Python (python)

Expected Output:

[1 2 3 4]
+ Hint

Use a boolean mask with the np.in1d() function

+ Show Solution
import numpy as np

a = np.array([1, 2, 3, 4, 5])
b = np.array([5, 6, 7, 8, 9])

# Create a boolean mask where `a`'s elements are NOT in `b`
mask = np.in1d(a, b)

# Use the `~` operator to invert the mask (get the opposite)
result = a[~mask]
print(result)Code language: Python (python)

Explanation:

  • The np.in1d() function checks if each element of the first array is also present in the second array, returning a boolean array.
  • The ~ operator is the bitwise NOT operator, which inverts the boolean mask (e.g., True becomes False). We use this inverted mask to select only the elements from a that are not present in b.

Exercise 23: Normalize a NumPy array (values between 0 and 1)

Given:

import numpy as np
arr = np.array([10, 20, 30, 40, 50])Code language: Python (python)

Expected Output:

Normalized Array: [0.   0.25 0.5  0.75 1.  ]
+ Hint

Use formula: arr - arr.min()) / (arr.max() - arr.min()).

+ Show Solution
import numpy as np

arr = np.array([10, 20, 30, 40, 50])
normalized = (arr - arr.min()) / (arr.max() - arr.min())
print("Normalized Array:", normalized)Code language: Python (python)

Explanation:

  • Subtract the minimum value so the smallest becomes 0.
  • Divide by the range (max - min) so the largest becomes 1.
  • This scales all values into [0, 1].

Exercise 24: Get the positions where elements of array a and b match

Given:

import numpy as np

a = np.array([1, 2, 3, 4, 5])
b = np.array([1, 4, 3, 7, 8])Code language: Python (python)

Expected Output:

(array([0, 2]),)
+ Hint

Use np.where() with a condition.

+ Show Solution
import numpy as np

a = np.array([1, 2, 3, 4, 5])
b = np.array([1, 4, 3, 7, 8])

# Use np.where() to find the index where the values match
index = np.where(a == b)
print(index)Code language: Python (python)

Explanation: The np.where() function returns the indices of elements in an array that satisfy a given condition. In this case, the condition a == b creates a boolean array, and np.where() returns the index of the True value(s)

Exercise 25: Extract numbers from an array

Write a code to extract all numbers from an array that are between 5 and 10 (inclusive).

Given:

import numpy as np
arr = np.arange(15)Code language: Python (python)

Expected Output:

[ 5  6  7  8  9 10]
+ Hint

Combine two boolean masks using the bitwise AND operator (&).

+ Show Solution
import numpy as np

arr = np.arange(15)
result = arr[(arr >= 5) & (arr <= 10)]
print(result)Code language: Python (python)

Explanation:

  • We create two separate boolean masks: arr >= 5 and arr <= 10.
  • We then use the bitwise AND operator & to combine them. This creates a new mask where True is only at positions where both conditions are met.
  • This combined mask is then used to select the desired elements from the original array.

Exercise 26: Create a random 3×2 matrix and find its maximum and minimum values

Expected Output (can vary):

[[0.9 0.05]
[0.7 0.2]
[0.4 0.6]]
Max Value: 0.9
Min Value: 0.05
+ Hint

Use np.random.random() with np.max() and np.min().

+ Show Solution
import numpy as np

rand_arr = np.random.rand(3, 2)
print(rand_arr)Code language: Python (python)

Explanation: The np.random.rand() function creates an array of a specified shape with random numbers from a uniform distribution over [0, 1). The arguments represent the dimensions of the desired array.

Exercise 27: Sorting a NumPy array based on a specific column

Given:

import numpy as np
sampleArray = np.array([[34, 43, 73], [82, 22, 12], [53, 94, 66]])Code language: Python (python)

Expected Output:

Original array:
[[34 43 73]
[82 22 12]
[53 94 66]]

Sorted array:
[[82 22 12]
[34 43 73]
[53 94 66]]
+ Hint

Get the indices that would sort an array’s elements using np.argsort(). Then, you can use these indices to reorder the rows of the original array

+ Show Solution
import numpy as np

sampleArray = np.array([[34, 43, 73], [82, 22, 12], [53, 94, 66]])

# Get the indices that would sort the array by its second column
sorted_indices = sampleArray[:, 1].argsort()

# Use the sorted indices to reorder the rows of the array
sorted_array = sampleArray[sorted_indices]

print("Original array:")
print(sampleArray)

print("\nSorted array:")
print(sorted_array)Code language: Python (python)

Explanation:

The solution uses np.argsort() on the second column to get the correct row order.

  • sampleArray[:, 1] selects the second column of the array. The : means “select all rows,” and the 1 specifies the column index (since indexing starts at 0).
  • .argsort(): This method is called on the selected column. It does not sort the column itself but returns the indices that would sort it. For the column [43, 22, 94], the sorted order would be [22, 43, 94], and the corresponding original indices are [1, 0, 2]. This is the output of .argsort().
  • By using these indices to reorder the rows of the sampleArray, you get a new array that is sorted based on the values in the second column.

Exercise 28: Delete and Insert a Column in a NumPy Array

Delete the second column from a given array and insert the following new column in its place.

Given:

import numpy as np

sampleArray = np.array([[34,43,73],[82,22,12],[53,94,66]])
newColumnToAdd = np.array([10, 10, 10])Code language: Python (python)

Expected Output:

[[34 10 73]
[82 10 12]
[53 10 66]]
+ Hint

Use np.delete() to remove the second column and then np.insert() to add the new one. Use axis=1 to make sure the operation is performed on the columns.

+ Show Solution
import numpy as np

sampleArray = np.array([[34,43,73],[82,22,12],[53,94,66]])
newColumn = np.array([10, 10, 10]) # Use a 1D array for simplicity

# Delete the second column (index 1)
# axis=1 specifies that the operation should be on columns
deletedArray = np.delete(sampleArray, 1, axis=1)

# Insert the new column at the second position (index 1)
# axis=1 specifies that we're inserting a column
resultArray = np.insert(deletedArray, 1, newColumn, axis=1)

print(resultArray)Code language: Python (python)

Explanation:

To perform this task, we use a two-step process:

  1. Delete the column: The np.delete() function removes a specified column. We pass it the original sampleArray, the index of the column we want to delete (1), and the argument axis=1 to tell NumPy that we’re performing the operation on a column.
  2. Insert the new column: The np.insert() function adds a new column to the array. We pass it the modified array (deletedArray), the index where the new column should go (1), the data for the newColumn, and again, the axis=1 to ensure it’s treated as a column. NumPy automatically handles broadcasting the newColumn to the correct shape to fit into the array.

Exercise 29: Swap column 1 and 2 in a 2D array

Given:

import numpy as np
arr = np.arange(9).reshape(3, 3)
# The columns are at index 0, 1, 2. We want to rearrange to 0, 2, 1Code language: Python (python)

Expected Output:

Before
[[0 1 2]
[3 4 5]
[6 7 8]]

After
[[0 2 1]
[3 5 4]
[6 8 7]]
+ Hint

Use advanced indexing with a list of column indices

+ Show Solution
import numpy as np

arr = np.arange(9).reshape(3, 3)
print("Before")
print(arr)
# The columns are at index 0, 1, 2. We want to rearrange to 0, 2, 1

arr[:, [1, 2]] = arr[:, [2, 1]]
print("After")
print(arr)Code language: Python (python)

Explanation:

  • This is a neat trick using NumPy’s indexing capabilities. arr[:, [1, 2]] selects all rows (:) and columns 1 and 2.
  • We then assign the values from arr[:, [2, 1]], which selects all rows but with columns 2 and 1 in that order. This effectively swaps the data between the two columns.

Exercise 30: Generate 10 random integers between 1 and 100

+ Hint

Use np.random.randint(low, high, size).

+ Show Solution
import numpy as np

arr = np.random.randint(1, 101, size=10)
print("Random Integers:", arr)Code language: Python (python)

Explanation:

  • low=1, high=101 (exclusive:- integers from 1 to 100.
  • size=10: generate 10 random integers.

Exercise 31: Create a 3×3 array of random integers and sort it row-wise

+ Hint

Use np.sort() with axis=1.

+ Show Solution
import numpy as np

arr = np.random.randint(1, 50, size=(3, 3))
print("Original Array:\n", arr)

sorted_arr = np.sort(arr, axis=1)
print("Row-wise Sorted Array:\n", sorted_arr)Code language: Python (python)

Explanation:

  • axis=1: sorts elements row by row.
  • Each row is arranged in ascending order.

Exercise 32: Shuffle an array randomly

Given:

import numpy as np
arr = np.arange(10)Code language: Python (python)

Expected Output (can vary):

Original Array: [0 1 2 3 4 5 6 7 8 9]
Shuffled Array: [4 8 6 1 2 3 5 7 9 0]
+ Hint

Use np.random.shuffle().

+ Show Solution
import numpy as np

arr = np.arange(10)
print("Original Array:", arr)

np.random.shuffle(arr)
print("Shuffled Array:", arr)Code language: Python (python)

Explanation:

  • np.random.shuffle() randomly reorders elements in-place.
  • Every run gives a different order.

Exercise 33: Create a 5×5 2D array with 1s on the border and 0s inside.

Expected Output:

[[1. 1. 1. 1. 1.]
[1. 0. 0. 0. 1.]
[1. 0. 0. 0. 1.]
[1. 0. 0. 0. 1.]
[1. 1. 1. 1. 1.]]
+ Hint

Create an array of 1s and then use slicing to change the inner values to 0.

+ Show Solution
import numpy as np

arr = np.ones((5, 5))
arr[1:-1, 1:-1] = 0
print(arr)Code language: Python (python)

Explanation:

  • We start by creating a 5×5 array of ones using np.ones().
  • Then, we use slicing to access the inner part of the array. The slice 1:-1 means “start at index 1 and go up to, but not including, the last element.”
  • So, arr[1:-1, 1:-1] selects rows 1 through 3 and columns 1 through 3, which is the inner 3×3 square. We then assign all of these elements to 0.

Exercise 34: Check if an array contains any NaN values.

Given:

import numpy as np
a = np.array([1, 2, np.nan, 4, 5])Code language: Python (python)

Expected Output:

True
+ Hint

Use np.isnan() and np.any().

+ Show Solution
import numpy as np

a = np.array([1, 2, np.nan, 4, 5])
has_nan = np.isnan(a).any()
print(has_nan)Code language: Python (python)

Explanation:

  • First, np.isnan(a) creates a boolean array where True corresponds to NaN values.
  • Then, we use the .any() method on this boolean array.
  • The .any() method returns True if any element of the array is True, making it a simple way to check for the presence of NaNs.

Exercise 35: Sort the rows of a 2D array based on the values of the second column

Given:

import numpy as np
arr = np.array([[8, 4, 1],
                [5, 2, 7],
                [6, 9, 3]])Code language: Python (python)

Expected Output:

[[5 2 7]
[8 4 1]
[6 9 3]]
+ Hint

Use np.argsort() on the second column to get the sorted indices, then use those indices to reorder the rows of the original array.

+ Show Solution
import numpy as np

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

# Get the indices that would sort the second column
sorted_indices = arr[:, 1].argsort()

# Use the indices to sort the entire array's rows
sorted_arr = arr[sorted_indices]
print(sorted_arr)Code language: Python (python)

Explanation:

  • The np.argsort() function returns the indices that would sort an array.
  • We apply it to arr[:, 1], which is the second column. This gives us the order in which the rows should be arranged to be sorted by that column.
  • We then use this array of indices to reorder the rows of the original array arr, resulting in a new sorted array.

Exercise 36: Flatten a multi-dimensional NumPy array

Write a code to Convert a 2D array into a 1D array.

Given:

import numpy as np
arr = np.array([[1, 2], [3, 4], [5, 6]])Code language: Python (python)

Expected Output:

Original Array:
[[1 2]
[3 4]
[5 6]]
Flattened Array: [1 2 3 4 5 6]
+ Hint

Use flatten() or ravel().

+ Show Solution
import numpy as np

arr = np.array([[1, 2], [3, 4], [5, 6]])
flattened = arr.flatten()

print("Original Array:\n", arr)
print("Flattened Array:", flattened)Code language: Python (python)

Explanation:

  • flatten() returns a copy of the array in 1D form.
  • ravel() can also be used, but it may return a view instead of a copy.

Exercise 37: Stack two arrays vertically and horizontally

Given:

import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])Code language: Python (python)

Expected Output:

Vertical Stack:
[[1 2 3]
[4 5 6]]
Horizontal Stack:
[1 2 3 4 5 6]
+ Hint

Use np.vstack() and np.hstack().

+ Show Solution
import numpy as np

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

v_stack = np.vstack((a, b))
h_stack = np.hstack((a, b))

print("Vertical Stack:\n", v_stack)
print("Horizontal Stack:\n", h_stack)Code language: Python (python)

Explanation:

  • vstack() → stacks arrays row-wise (top to bottom).
  • hstack() → stacks arrays column-wise (side by side).

Exercise 38: Split an array into 3 equal parts

Split a 1D array of 9 elements into 3 equal parts.

Given:

import numpy as np
arr = np.arange(9)Code language: Python (python)

Expected Output:

Original Array: [0 1 2 3 4 5 6 7 8]
Split Arrays: [array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8])]
+ Hint

Use np.split(array, parts).

+ Show Solution
import numpy as np

arr = np.arange(9)
split_arr = np.split(arr, 3)

print("Original Array:", arr)
print("Split Arrays:", split_arr)Code language: Python (python)

Explanation: np.split(arr, 3) divides the array into 3 equal parts. Each part is a smaller NumPy array.

Exercise 39: Perform Addition and Squaring on Arrays

Given:

import numpy as np

arrayOne = np.array([[5, 6, 9], [21, 18, 27]])
arrayTwo = np.array([[15, 33, 24], [4, 7, 1]])Code language: Python (python)

Expected Output:

Result of array addition:
[[20 39 33]
[25 25 28]]

Result with each element squared:
[[ 400 1521 1089]
[ 625 625 784]]
+ Hint

Perform vectorized operations directly on NumPy arrays. This means you can add two arrays together with the + operator and square them using the ** 2 operator

+ Show Solution
import numpy as np

arrayOne = np.array([[5, 6, 9], [21, 18, 27]])
arrayTwo = np.array([[15, 33, 24], [4, 7, 1]])

# Add the two arrays
resultArray = arrayOne + arrayTwo

print("Result of array addition:")
print(resultArray)

# Square each element of the resultArray
squaredArray = resultArray ** 2

print("\nResult with each element squared:")
print(squaredArray)Code language: Python (python)

Explanation:

  • Addition (+): When you use the + operator on two NumPy arrays of the same shape, it performs element-wise addition.
  • Squaring (** 2): Similarly, the ** operator works element-wise.

Exercise 40: Invert a matrix

Given:

import numpy as np
arr = np.array([[1, 2], [3, 4]])Code language: Python (python)

Expected Output:

[[-2.   1. ]
[ 1.5 -0.5]]
+ Hint

Use the np.linalg.inv() function.

+ Show Solution
import numpy as np

arr = np.array([[1, 2], [3, 4]])
inv_arr = np.linalg.inv(arr)
print(inv_arr)Code language: Python (python)

Explanation: The np.linalg module contains a wide range of linear algebra functions. np.linalg.inv() calculates the inverse of a square matrix. The inverse matrix, when multiplied by the original matrix, results in the identity matrix.

Exercise 41: Use boolean indexing to filter values less than a given number

From an array, return values less than 30.

Given:

import numpy as np
arr = np.array([5, 12, 29, 30, 44, 7, 18])Code language: Python (python)

Expected Output:

Values < 30: [ 5 12 29  7 18]
+ Hint

Build a mask arr < 30 and apply it.

+ Show Solution
import numpy as np

arr = np.array([5, 12, 29, 30, 44, 7, 18])
filtered = arr[arr < 30]
print("Values < 30:", filtered)Code language: Python (python)

Explanation: Comparisons on arrays return boolean masks that can be used to filter elements meeting a condition.

Exercise 42: Count the number of occurrences of each unique element

Given:

import numpy as np
arr = np.array([2, 3, 2, 5, 3, 3, 2, 5])Code language: Python (python)

Expected Output:

Value 2 occurs 3 time(s)
Value 3 occurs 3 time(s)
Value 5 occurs 2 time(s)
+ Hint

Use np.unique(..., return_counts=True).

+ Show Solution
import numpy as np

arr = np.array([2, 3, 2, 5, 3, 3, 2, 7, 5])
vals, counts = np.unique(arr, return_counts=True)
for v, c in zip(vals, counts):
    print(f"Value {v} occurs {c} time(s)")Code language: Python (python)

Explanation: np.unique returns sorted unique values and, with return_counts=True, the frequency of each value.

Exercise 43: Find the intersection and union of two arrays

  • Intersection: elements present in both arrays.
  • Union: all unique elements from both arrays, sorted.

Given:

import numpy as np

a = np.array([1, 2, 3, 5, 7])
b = np.array([3, 4, 5, 6, 7])Code language: Python (python)

Expected Output:

Intersection: [3 5 7]
Union: [1 2 3 4 5 6 7]
+ Hint

Use np.intersect1d() and np.union1d().

+ Show Solution
import numpy as np

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

intersection = np.intersect1d(a, b)
union = np.union1d(a, b)

print("Intersection:", intersection)
print("Union:", union)Code language: Python (python)

Exercise 44: Transpose a matrix

Transposing a matrix means flipping it over its diagonal.

Given:

import numpy as np
arr = np.array([[1, 2], [3, 4]])Code language: Python (python)

Expected Output:

[[1 3]
[2 4]]
+ Hint

Use the .T attribute or np.transpose().

+ Show Solution
import numpy as np

arr = np.array([[1, 2], [3, 4]])
transposed_arr = arr.T
print(transposed_arr)Code language: Python (python)

Explanation: The .T attribute is a convenient and commonly used shortcut to get the transposed view of an array without creating a copy. np.transpose() does the same thing but as a function.

Exercise 45: Compute the eigenvalues and eigenvectors of a matrix

For a square matrix, compute its eigenvalues and eigenvectors.

Given:

import numpy as np
A = np.array([[4, 2],
              [1, 3]])Code language: Python (python)

Expected Output:

Eigenvalues:
[5. 2.]
Eigenvectors (columns):
[[ 0.89442719 -0.70710678]
[ 0.4472136 0.70710678]]
+ Hint

Use np.linalg.eig().

+ Show Solution
import numpy as np

A = np.array([[4, 2],
              [1, 3]])

eigvals, eigvecs = np.linalg.eig(A)
print("Eigenvalues:\n", eigvals)
print("Eigenvectors (columns):\n", eigvecs)Code language: Python (python)

Explanation: np.linalg.eig(A) returns eigenvalues and the corresponding eigenvectors (each column in eigvecs is an eigenvector of A).

Exercise 46: Solve a linear equation

Solve the system of linear equations: x + 2y = 8 and 3x + 4y = 18.

+ Hint

Represent the equations as a matrix problem Ax = b and use np.linalg.solve().

+ Show Solution
import numpy as np

# Define the coefficient matrix A
A = np.array([[1, 2], [3, 4]])

# Define the right-hand side vector b
b = np.array([8, 18])

# Solve for x and y
solution = np.linalg.solve(A, b)
print(solution)Code language: Python (python)

Explanation: NumPy is excellent for solving linear equations. We first represent the system as Ax = b, where A is the matrix of coefficients, x is the vector of variables we want to solve for, and b is the vector of constants. np.linalg.solve(A, b) is a very efficient and accurate way to find the x vector.

Exercise 47: Create an 8×8 checkerboard pattern using 0s and 1s

Given:

import numpy as np
arr = np.array([10, 20, 30, 100, 200, 300])Code language: Python (python)

Expected Output:

[[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]
[0 1 0 1 0 1 0 1]
[1 0 1 0 1 0 1 0]]
+ Hint

Use slicing and the modulo operator (%)

+ Show Solution
import numpy as np

# Create an 8x8 array of zeros
checkerboard = np.zeros((8, 8), dtype=int)

# Use slicing and a step of 2 to set alternating elements
checkerboard[1::2, ::2] = 1
checkerboard[::2, 1::2] = 1
print(checkerboard)Code language: Python (python)

Explanation:

  • We create an 8×8 array of zeros. The trick is in the slicing. 1::2 means “start at index 1 and take every second element.” ::2 means “start at index 0 and take every second element.”
  • By applying these steps to the rows and columns, we can efficiently set the alternating pattern of 1s without needing a loop.

Exercise 48: Find nearest value

Find the value in an array that is closest to a number 3.

Given:

import numpy as np
arr = np.array([1.5, 2.8, 3.2, 4.1])Code language: Python (python)

Expected Output:

The value closest to 3 is: 2.8
+ Hint

Subtract the given number from the array, take the absolute value, and then find the index of the minimum value using np.abs() and np.argmin().

+ Show Solution
import numpy as np

arr = np.array([1.5, 2.8, 3.2, 4.1])
target_value = 3

# Find the index of the minimum absolute difference
index = np.abs(arr - target_value).argmin()

# Use the index to get the value
nearest_value = arr[index]
print(f"The value closest to {target_value} is: {nearest_value}")Code language: Python (python)

Explanation:

  • This is a neat two-step process. First, we perform a vectorized subtraction of the target_value from the entire array. Then, we take the np.abs() of the result to get the positive distance from the target for each element.
  • Finally, np.argmin() returns the index of the element with the smallest value (i.e., the smallest distance), which we then use to retrieve the corresponding value from the original array.

Exercise 49: Convert to object array

Convert a 1D array to an object array, retaining the original data type of each element.

Given:

import numpy as np
arr = np.array([1, 'a', 3, 4, 5]) Code language: Python (python)

Expected Output:

Zeros: [0. 0. 0. 0. 0.]
Ones: [1. 1. 1. 1. 1.]
+ Hint

Create a new empty object array and fill it with the elements..

+ Show Solution
import numpy as np

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

# Create an empty object array with the same size
obj_arr = np.empty(arr.size, dtype='object')

# Assign the elements from the original array
obj_arr[:] = arr

# We can now add a string element to it
obj_arr[1] = 'a'
print(obj_arr)
print(obj_arr.dtype)Code language: Python (python)

Explanation:

  • A standard NumPy array can only hold elements of the same data type. An object array is a special type of array that can hold Python objects of different types, similar to a regular Python list.
  • We create an empty array with dtype='object' and then use slicing to copy the elements over. This allows us to store mixed data types like integers and strings in a single NumPy array.

Exercise 50: Compute the mean, median, and standard deviation of a NumPy array

Given:

import numpy as np
arr = np.array([10, 20, 30, 100, 200, 300])Code language: Python (python)

Expected Output:

Zeros: [0. 0. 0. 0. 0.]
Ones: [1. 1. 1. 1. 1.]
+ Hint

Use np.mean(), np.median(), np.std().

+ Show Solution
import numpy as np

zeros_arr = np.zeros(5)
ones_arr = np.ones(5)

print("Zeros:", zeros_arr)
print("Ones:", ones_arr)Code language: Python (python)

Explanation:

  • np.ones(5) → Creates [1. 1. 1. 1. 1.]
  • np.zeros(5) → Creates [0. 0. 0. 0. 0.]

Filed Under: Python, Python Exercises

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Image

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Loading comments... Please wait.

In: Python Python Exercises
TweetF  sharein  shareP  Pin

  Python Exercises

  • All Python Exercises
  • Basic Exercise for Beginners
  • Input and Output Exercise
  • Loop Exercise
  • Functions Exercise
  • String Exercise
  • Data Structure Exercise
  • List Exercise
  • Dictionary Exercise
  • Set Exercise
  • Tuple Exercise
  • Date and Time Exercise
  • OOP Exercise
  • File Handling Exercise
  • Python JSON Exercise
  • Random Data Generation Exercise
  • NumPy Exercise
  • Pandas Exercise
  • Matplotlib Exercise
  • Python Database Exercise

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2025 pynative.com

Advertisement