NumPy: Find the number of elements of an array, length of one array element in bytes
NumPy: Array Object Exercise-16 with Solution
Write a NumPy program to find the number of elements in an array. It also finds the length of one array element in bytes and the total bytes consumed by the elements.
Pictorial Presentation:
Sample Solution:
Python Code:
# Importing the NumPy library with an alias 'np'
import numpy as np
# Creating an array 'x' with specified data type 'float64'
x = np.array([1, 2, 3], dtype=np.float64)
# Printing the size of the array 'x'
print("Size of the array: ", x.size)
# Printing the length of one array element in bytes
print("Length of one array element in bytes: ", x.itemsize)
# Printing the total bytes consumed by the elements of the array 'x'
print("Total bytes consumed by the elements of the array: ", x.nbytes)
Sample Output:
Size of the array: 3 Length of one array element in bytes: 8 Total bytes consumed by the elements of the array: 24
Explanation:
In the above code -
x = np.array([1,2,3], dtype=np.float64): Creates a NumPy array with elements 1, 2, and 3, and with the specified dtype of float64.
print("Size of the array: ", x.size): Prints the size (number of elements) of the array, which is 3 in this case.
print("Length of one array element in bytes: ", x.itemsize): Prints the length (size) of one array element in bytes, which is 8 bytes for a float64.
print("Total bytes consumed by the elements of the array: ", x.nbytes): Prints the total bytes consumed by the elements of the array, which is the size (3 elements) multiplied by the itemsize (8 bytes) = 24 bytes.
Python-Numpy Code Editor:
Previous: Write a NumPy program to find the real and imaginary parts of an array of complex numbers
Next: Write a NumPy program to test whether each element of a 1-D array is also present in a second array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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-16.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics