w3resource

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

NumPy: Array Object Exercise-174 with Solution

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.

Python-Numpy Code Editor:

Previous: Write a NumPy program to set zero to lower triangles along the last two axes of a three-dimensional of a given array.
Next: Write a NumPy program to create an 1-D array of 20 elements. Now create a new array of shape (5, 4) from the said array, then restores the reshaped array into a 1-D array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/python-numpy-exercise-174.php