w3resource

NumPy: Count the number of dimensions, number of elements and number of bytes for each element in a given array

NumPy: Array Object Exercise-133 with Solution

Write a NumPy program to count the number of dimensions, number of elements and number of bytes for each element in a given array.

Sample Solution:

Python Code:

import numpy as np    
print("\nOriginal arrays:")
x = np.array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]])
print(x)
print("\nNumber of dimensions:")
print(x.ndim)
print("Number of elements:")
print(x.size)
print("Number of bytes for each element in the said array:")
print(x.itemsize) 

Sample Output:

Original arrays:
[[ 0  1  2  3  4  5  6  7  8  9 10 11]
 [12 13 14 15 16 17 18 19 20 21 22 23]]

Number of dimensions:
2
Number of elements:
24
Number of bytes for each element in the said array:
8

Pictorial Presentation:

Python NumPy: Count the number of dimensions, number of elements and number of bytes for each element in a given array.

Python Code Editor:

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

Previous: Write a NumPy program to split array into multiple sub-arrays along the 3rd axis.
Next: Write a NumPy program to extract all the elements of the first row from a given (4x4) array.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Set comprehension:

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