nbytes reflects only the raw element data stored in the array's underlying buffer — it doesn't include the small amount of additional memory Python and NumPy use for the array object itself, its shape, dtype, and other metadata, so it's a slight underestimate of the object's true total memory footprint, though for any array of meaningful size, the metadata overhead is negligible in comparison. It's a quick, direct way to estimate whether a planned array will fit comfortably in available memory before actually allocating it.
1Understanding ndarray.nbytes
nbytes reflects only the raw element data stored in the array's underlying buffer — it doesn't include the small amount of additional memory Python and NumPy use for the array object itself, its shape, dtype, and other metadata, so it's a slight underestimate of the object's true total memory footprint, though for any array of meaningful size, the metadata overhead is negligible in comparison. It's a quick, direct way to estimate whether a planned array will fit comfortably in available memory before actually allocating it.
Check .nbytes before allocating a very large array, or several of them, to sanity-check that the numbers make sense — it's an easy way to catch an accidental extra zero in a shape calculation before it crashes the program with a memory error.
import numpy as np
arr = np.zeros((1000, 1000), dtype=np.float64)
print(arr.nbytes)2Practical Example
Here is a real-world application of ndarray.nbytes showing how it is used in production NumPy code.
import numpy as np
big = np.zeros(1_000_000, dtype=np.float64)
small = big.astype(np.float32)
print(big.nbytes, small.nbytes)3Best Practices
Follow these guidelines when working with ndarray.nbytes:
1. Check .nbytes before allocating unusually large arrays, to catch shape miscalculations before they exhaust available memory
2. Choose a smaller dtype deliberately when nbytes matters, since it directly scales with itemsize
3. Remember .nbytes measures only the array's raw data, not the small additional overhead of the Python/NumPy object wrapping it
Tip: Check .nbytes before allocating a very large array, or several of them, to sanity-check that the numbers make sense — it's an easy way to catch an accidental extra zero in a shape calculation before it crashes the program with a memory error.
import numpy as np
arr = np.zeros((1000, 1000), dtype=np.float64)
print(arr.nbytes)