NumPy ndarray.itemsize Attribute



The NumPy ndarray.itemsize attribute is used to get the size (in bytes) of each element in a NumPy array. It helps in understanding the memory consumption of the array, which is important when dealing with large datasets or optimizing memory usage.

Knowing the item size can be useful when working with large arrays to estimate the total memory usage or when performing memory-efficient computations.

The itemsize attribute gives the size of individual elements, and can also be combined with the size attribute to calculate the total memory consumption of the array.

Usage of the itemsize Attribute in NumPy

The itemsize attribute can be accessed directly from a NumPy array object to determine the size of each element in the array.

It is useful when you need to understand the memory overhead of your data before performing large-scale computations or storing large arrays.

Below are some examples that demonstrate how itemsize can be applied to various arrays in NumPy.

Example: Basic Usage of itemsize Attribute

In this example, we create a simple 1-dimensional array and use the itemsize attribute to find out the size (in bytes) of each element −

import numpy as np

# Creating a 1-dimensional array with integer elements
arr = np.array([1, 2, 3, 4])
print(arr.itemsize)

Following is the output obtained −

8

Example: Checking itemsize of a 2D Array

In this example, we create a 2-dimensional array and use the itemsize attribute to determine the size of each element −

import numpy as np

# Creating a 2-dimensional array with float elements
arr = np.array([[1.1, 2.2, 3.3], [4.4, 5.5, 6.6]])
print(arr.itemsize)

This will produce the following result −

8

Example: itemsize with Complex Data Types

In this example, we create an array of complex numbers and use the itemsize attribute to find out the size of each element −

import numpy as np

# Creating an array of complex numbers
arr = np.array([1+2j, 3+4j, 5+6j])
print(arr.itemsize)

Following is the output of the above code −

16

Example: itemsize with String Elements

In this example, we create a 1-dimensional array with string elements and use the itemsize attribute to check the size of each element −

import numpy as np

# Creating a 1-dimensional array with string elements
arr = np.array(['apple', 'banana', 'cherry'])
print(arr.itemsize)

The output obtained is as shown below −

24
numpy_array_attributes.htm
Advertisements