All sample questions / NumPy
What does print(a.reshape(4, -1).shape) print? NumPy Views, Copies and Reshape
Block 4, Views, Copies and Reshape, question 10 of the NumPy sample
import numpy as np
a = np.arange(6)
print(a.reshape(4, -1).shape)
What does this print?
Show the answer and why each option is right or wrong
Answer, C. ValueError
- A. (4, 2)
- Assumes -1 rounds up to the nearest whole number of columns instead of requiring an exact division.
- B. (4, 1)
- Assumes a single column is produced regardless of whether the element count actually divides evenly by the fixed axis.
- C. ValueError
- Correct. 6 elements split across 4 rows would need 1.5 columns, which is not a whole number, so NumPy raises ValueError instead of producing a shape that could not hold every element exactly once.
- D. (4, 6)
- Assumes reshape repeats some elements to fill out an inexact shape.
Just like reshape(-1, 4), fixing one axis and asking for -1 on the other only succeeds when the total element count divides evenly by the fixed size. Four does not divide six evenly, so there is no valid whole number for the other axis and the call fails.
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.