Every ndarray element has a fixed dtype (data type). Dtypes control memory size, precision, and which operations are valid.
Common dtypes
int8/int16/int32/int64— signed integersfloat32/float64— IEEE floats (default float is usually float64)bool_— True/Falseobject— Python object references (slow, avoid when possible)
Casting and itemsize
import numpy as np
a = np.array([1, 2, 3], dtype=np.float32)
print(a.dtype, a.itemsize) # 4 bytes per element
Type promotion
Operations between dtypes promote to a common type—mixing int and float yields float. Explicit .astype() controls conversions; watch for truncation when casting float to int.
Important interview questions and answers
- Q: float32 vs float64?
A: float32 uses half the memory; float64 has more precision—ML often uses float32 on GPU. - Q: object dtype?
A: Stores pointers to Python objects—breaks vectorization speed benefits.
Self-check
- How many bytes per float64 element?
- What method converts an array to a different dtype?
Pitfall: Casting float to int truncates—use np.round first if needed.
Interview prep
- float32 vs float64?
float32 half memory; float64 more precision—ML often uses float32 on GPU.
- astype?
Casts array to new dtype—watch truncation float→int.