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:

import numpy as np
array_nums = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print("Original array:")
print(array_nums)
print("\nNumber of items of the said array:")
print(array_nums.size) 
print("\nArray dimensions:")
print(array_nums.shape)
print("\nNumber of array dimensions:")
print(array_nums.ndim)
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

Python Code Editor:

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

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 Python skills with w3resource's quiz



Python: Tips of the Day

List comprehension:

>>> m = [x ** 2 for x in range(5)]
>>> m
[0, 1, 4, 9, 16]