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:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Printing a message indicating the original array will be displayed
print("\nOriginal arrays:")

# Creating a NumPy array 'x' containing two nested lists with integers from 0 to 23 and shaping it into a 2x12 array
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]])

# Displaying the original 2D array 'x'
print(x)

# Printing a message indicating the number of dimensions of the array using x.ndim
print("\nNumber of dimensions:")
print(x.ndim)

# Printing a message indicating the total number of elements in the array using x.size
print("Number of elements:")
print(x.size)

# Printing a message indicating the number of bytes for each element in the array using x.itemsize
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

Explanation:

In the above exercise -

x = np.array([...]): This line creates a 2-dimensional NumPy array x with the given elements.

print(x.ndim): It prints the number of dimensions of the array x.

print(x.size): It prints the total number of elements in the array x. In this case, it will print 24 because x has 2 rows and 12 columns (2 * 12 = 24 elements).

print(x.itemsize): It prints the size in bytes of each element of the array x. In this case, since the elements are integers, it will typically print 4 or 8 depending on the default integer size of the platform (32-bit or 64-bit).

Pictorial Presentation:

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

Python-Numpy Code Editor:

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 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://w3resource.com/python-exercises/numpy/python-numpy-exercise-133.php