All sample questions / NumPy
NumPy Arrays, dtypes and Scalars, what does print(b.dtype) print after a = np.array([1, 2, 3], dtype=np.float32)?
Block 1, Arrays, dtypes and Scalars, question 3 of the NumPy sample
import numpy as np
a = np.array([1, 2, 3], dtype=np.float32)
b = a + 1.5
print(b.dtype)
What does this print?
Show the answer and why each option is right or wrong
Answer, B. float32
- A. int64
- Assumes mixing a float32 array with a Python float drops back to a whole number dtype.
- B. float32
- Correct. The same NEP 50 rule applies to floats, a Python float added to a float32 array keeps the result float32 rather than upgrading it to float64.
- C. float64
- Assumes the bare Python float on the right widens the result to the default double precision dtype, the way older NumPy versions behaved.
- D. object
- Assumes this kind of mixed operation needs a generic object dtype to represent the result.
A Python scalar in an arithmetic operation no longer forces the array to a wider dtype based on its own kind, it only has to fit within the dtype the array already has. A float32 array plus a Python float stays float32 under this rule.
The answer above is what NumPy 2.4.4 printed when the snippet was run, not what someone expected it to do.
This question comes from a bank of 279 NumPy interview questions, all built the same way, sold as one PDF with the full answer key.
Get the 279 NumPy questions, 9 euros
Or SQL, Python, pandas and NumPy together, 1,636 questions, 19 euros
Or play the free NumPy sample, twenty questions in the browser, also as a free PDF.
Previous question Next question
Did this save you a lookup? Buy me a coffee on Ko-fi.