NumPy
1 min read
Updated 4 Aug 2026
4. Data Types (dtypes)
NumPy dtypes control memory and precision.
NumPy dtypes control memory and precision.
| Category | Examples | Notes |
|---|---|---|
| Integer | int8, int16, int32, int64, unsigned uint8… |
fixed width, can overflow silently |
| Float | float16, float32, float64 |
float64 is the default |
| Bool | bool_ |
1 byte each |
| Complex | complex64, complex128 |
real + imaginary |
| Object | object |
Python objects (slow, avoid) |
a = np.array([1, 2, 3], dtype=np.int8)
a[0] = 200 # overflow!
print(a) # [-56 2 3] (200 wraps around int8)
⚠️ Common Mistake: Integer overflow is silent.
int8holds only -128…127. Use a wider dtype for large values.
Changing dtypes & memory optimization#
big = np.arange(1_000_000) # int64 -> 8 MB
small = big.astype(np.int32) # -> 4 MB
print(big.nbytes, small.nbytes) # 8000000 4000000
🚀 Best Practice: Downcast to the smallest dtype that safely fits your data (
int32,float32) to halve memory on large datasets — crucial before feeding data to ML models.
⭐ Interview Question:
astypevsviewfor dtype change?astypeconverts values into a new buffer (safe). Reinterpreting bytes via.view(dtype)reuses the same bytes with a different interpretation (dangerous, rarely what you want).