w3resource

NumPy: Get the number of items, array dimensions, number of array dimensions and the memory size of each element of a given array


Get array metadata (dimensions, size, etc.).

Write a NumPy program to get the number of items, array dimensions, number of array dimensions and the memory size of each element of a given array.

Sample Solution:

Python Code:

# Importing NumPy library
import numpy as np

# Creating a 2D NumPy array
array_nums = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])

# Printing the original array
print("Original array:")
print(array_nums)

# Finding the number of items in the array
print("\nNumber of items of the said array:")
print(array_nums.size)

# Retrieving the shape of the array (number of rows and columns)
print("\nArray dimensions:")
print(array_nums.shape)

# Finding the number of dimensions of the array
print("\nNumber of array dimensions:")
print(array_nums.ndim)

# Determining the memory size (in bytes) of each array element
print("\nMemory size of each element of the said array")
print(array_nums.itemsize) 

Sample Output:

Original array:
[[ 1  2  3  4]
 [ 5  6  7  8]
 [ 9 10 11 12]]

Number of items of the said array:
12

Array dimensions:
(3, 4)

Number of array dimensions:
2

Memory size of each element of the said array
8

Explanation:

In the above code -

  • array_nums = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) creates a 2-dimensional NumPy array with 3 rows and 4 columns.
  • print(array_nums) prints the array.
  • print(array_nums.size) prints the total number of elements in the array (3 rows * 4 columns = 12).
  • print(array_nums.shape) prints the shape of the array as a tuple, in this case (3, 4), indicating 3 rows and 4 columns.
  • print(array_nums.ndim) prints the number of dimensions (axes) of the array, which is 2 for a 2-dimensional array.
  • print(array_nums.itemsize) prints the size (in bytes) of each element in the array.

For more Practice: Solve these Related Problems:

  • Write a NumPy program to print the shape, number of dimensions, total elements, and memory size of each element for a given array.
  • Create a function that summarizes an array’s metadata into a formatted string.
  • Implement a solution that compares metadata of two arrays to check if they share the same structure.
  • Test the metadata function on arrays with different dtypes and shapes to verify accurate reporting.

Go to:


PREV : Set lower triangles of a 3D array to zero.
NEXT : Reshape 1D array to 2D and restore.


Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.