NumPy Arrays - Answer Key

Authors

Noor Sohail

Will Gammerdinger

Published

March 15, 2026

Exercise 1

  1. Create a NumPy array holding the values 1, 14, 22, 47, 58 and 67 and assign it to exercise_array
# Create exercise_array
exercise_array = np.array([1, 14, 22, 47, 58, 67])
  1. Retrieve the second, third and fourth elements from exercise_array
# Retrieve second, third and fourth elements from exercise_array
print(exercise_array[1:4])
[14 22 47]
  1. Retrieve the values less than 25 from exercise_array
# Subset array to the values less than 25
print(exercise_array[exercise_array < 25])
[ 1 14 22]
  1. Reshape exercise_array into a matrix have three rows with two columns each and assign it to exercise_matrix.
# Reshape exercise_array to be a matrix of 3 rows and 2 columns
exercise_matrix = exercise_array.reshape(3, 2)

print(exercise_matrix)
[[ 1 14]
 [22 47]
 [58 67]]
  1. Retrieve the value in the third row, second column of exercise_matrix
# Retrieve the value in the third row, second column of exercise_matrix
print(exercise_matrix[2,1])
67

Exercise 2

  1. Test out the following functions on the reshaped_matrix array that we created earlier and describe what the output is for each function:
    • np.shape()
    • np.ndim()
    • np.size()
  • np.shape(): This function returns the dimensions of the array as a tuple. For example, np.shape on a 2 x 5 2-dimensional array would return (2, 5).
# Retrieve the dimensions of matrix_arange
np.shape(reshaped_matrix)
(2, 5)
  • np.ndim(): This function returns the number of dimensions of the array.
# Retrieve number of the dimensions of matrix_arange
np.ndim(reshaped_matrix)
2
  • np.size(): This function returns the total number of elements in the array. For example, np.size on a 2 x 5 2-dimensional array would return 10 (2 rows x 5 columns = 10 elements).
# Retrieve number of elements within matrix_arange
np.size(reshaped_matrix)
10

Reuse

CC-BY-4.0