All sample questions / NumPy

What does print((a + 127).tolist()) print? NumPy NaN, Overflow and Type Promotion

Block 6, NaN, Overflow and Type Promotion, question 15 of the NumPy sample

import numpy as np
a = np.array([1, 2], dtype=np.int8)
print((a + 127).tolist())

What does this print?

  1. A. OverflowError
  2. B. [126, 127]
  3. C. [-128, -127]
  4. D. [128, 129]
Show the answer and why each option is right or wrong

Answer, C. [-128, -127]

A. OverflowError
Assumes the Python int 127 does not fit an int8 array and must raise before any arithmetic happens.
B. [126, 127]
Subtracts instead of adds, as if the operator had been reversed.
C. [-128, -127]
Correct. 127 fits within int8 so the addition proceeds, but the true sums, 128 and 129, both overflow int8 and wrap to negative 128 and negative 127.
D. [128, 129]
Assumes the addition returns the true mathematical sums without wrapping them into the int8 range.

127 is itself a valid int8 value, so NEP 50 lets the addition proceed using the array dtype, it is only the arithmetic result that overflows and wraps. This is the same distinction as with uint8, an in range Python operand can still produce an out of range, silently wrapped result.

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.