NumPy: Create an array with the values 1, 7, 13, 105 and determine the size of the memory occupied by the array
NumPy: Basic Exercise-12 with Solution
Write a NumPy program to create an array with the values 1, 7, 13, 105 and determine the size of the memory occupied by the array.
This NumPy program creates an array with the specific values 1, 7, 13, and 105. It then calculates and outputs the size of the memory occupied by this array. By utilizing NumPy's memory management functions, the program provides insights into the memory footprint of the array.
Sample Solution :
Python Code :
# Importing the NumPy library with an alias 'np'
import numpy as np
# Creating a NumPy array 'X' containing elements 1, 7, 13, and 105
X = np.array([1, 7, 13, 105])
# Printing a message indicating the original array 'X'
print("Original array:")
print(X)
# Calculating the size of the memory occupied by the array 'X' (number of elements multiplied by the size of each element in bytes) and printing the result
print("Size of the memory occupied by the said array:")
print("%d bytes" % (X.size * X.itemsize))
Output:
Original array: [ 1 7 13 105] Size of the memory occupied by the said array: 32 bytes
Explanation:
At first we declare a NumPy array X = np.array([1, 7, 13, 105]).
print("%d bytes" % (X.size * X.itemsize)): This line calculates the total memory size occupied by the array 'X' in bytes and prints the result to the console. The memory size is determined by multiplying the number of elements in the array (X.size) by the size in bytes of each element. In this case, since the default data type of the array is int (usually int64 or int32, depending on the system), the item size will be 8 bytes for int64 or 4 bytes for int32. The total memory size in bytes is then calculated as follows:
For int64: 4 elements * 8 bytes/element = 32 bytes
For int32: 4 elements * 4 bytes/element = 16 bytes
The result, either "32 bytes" or "16 bytes", is printed to the console depending on the system.
Python-Numpy Code Editor:
Previous: NumPy program to create an element-wise comparison (equal, equal within a tolerance) of two given arrays.
Next: NumPy program to create an array of 10 zeros, 10 ones, 10 fives.
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/basic/numpy-basic-exercise-12.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics