NumPy ndarray.itemsize
The numpy.ndarray.itemsize
attribute returns the size of a single element in a NumPy array, measured in bytes.
It helps in understanding memory usage and optimizing performance when handling large arrays.
Syntax
ndarray.itemsize
Return Value
Returns an integer representing the size (in bytes) of one element in the NumPy array.
The size depends on the data type (dtype
) of the array.
Examples
1. Checking the Item Size of an Integer Array
This example demonstrates how to check the size (in bytes) of a single integer element in a NumPy array.
import numpy as np
# Create an array of integers
arr = np.array([1, 2, 3, 4, 5])
# Get the item size (size of a single element in bytes)
item_size = arr.itemsize
# Print the item size
print("Size of one element in bytes:", item_size)
Output:
Size of one element in bytes: 8
The output shows that each element in the array occupies 8 bytes (for a default 64-bit integer in NumPy).
2. Checking Item Size for Different Data Types
Here, we check how the item size varies for different data types.
import numpy as np
# Create arrays with different data types
arr_int32 = np.array([1, 2, 3], dtype=np.int32) # 32-bit integer
arr_float64 = np.array([1.0, 2.0, 3.0], dtype=np.float64) # 64-bit float
arr_bool = np.array([True, False, True], dtype=np.bool_) # Boolean type
# Print item sizes for each array
print("Item size of int32 array:", arr_int32.itemsize)
print("Item size of float64 array:", arr_float64.itemsize)
print("Item size of boolean array:", arr_bool.itemsize)
Output:
Item size of int32 array: 4
Item size of float64 array: 8
Item size of boolean array: 1
Here, a 32-bit integer requires 4 bytes, a 64-bit float takes 8 bytes, and a boolean type uses just 1 byte per element.
3. Using Item Size to Calculate Total Memory Usage
The total memory used by an array can be computed using itemsize
multiplied by the number of elements.
import numpy as np
# Create a large array
arr = np.ones((1000, 1000), dtype=np.float64) # 1 million elements
# Calculate memory usage
total_memory = arr.size * arr.itemsize # Number of elements * bytes per element
# Print the result
print("Total memory usage in bytes:", total_memory)
Output:
Total memory usage in bytes: 8000000
This example shows that a (1000,1000)
array of float64
values requires 8 MB of memory (since each float takes 8 bytes).