All sample questions / NumPy
What does print(a[np.newaxis, :].shape) print? NumPy Broadcasting and Shapes
Block 3, Broadcasting and Shapes, question 8 of the NumPy sample
import numpy as np
a = np.arange(3)
print(a[np.newaxis, :].shape)
What does this print?
Show the answer and why each option is right or wrong
Answer, C. (1, 3)
- A. (3, 1)
- Places the new axis after the existing one instead of before it.
- B. (1, 1, 3)
- Assumes np.newaxis inserts two new axes instead of exactly one.
- C. (1, 3)
- Correct. np.newaxis inserts a size 1 axis exactly where it appears in the index, before the existing axis, turning shape (3,) into (1, 3).
- D. (3,)
- Assumes indexing with np.newaxis alongside a full slice leaves the shape completely unchanged.
np.newaxis inserts exactly one size 1 axis at the position it occupies in the index tuple, everything else about the array stays the same. Putting it before the colon makes a row shape (1, 3), putting it after would make a column shape (3, 1) instead.
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.