How do you add a new axis to a NumPy array using np.newaxis or np.expand_dims, and why is this useful for broadcasting?

Quick Overview

Explain how to insert a length-1 axis into a NumPy array with np.newaxis or np.expand_dims and why that matters for broadcasting. Tests understanding of array shapes, NumPy's broadcasting rules, views versus copies, and the shape mistakes that cause silent bugs in data code.

How do you add a new axis to a NumPy array using np.newaxis or np.expand_dims, and why is this useful for broadcasting?

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: easy

Interview Round: Other

How do you add a new axis to a NumPy array using `np.newaxis` or `np.expand_dims`, and why is this useful for broadcasting? ```hint Look at the shapes Write the shapes of the two operands right-aligned, one above the other, and ask what each dimension pair needs before NumPy can stretch one array to match the other. ``` ### What a Strong Answer Covers - The syntax of both forms and the shape each one produces for a 1-D input - How NumPy's broadcasting rule decides whether two shapes are compatible - A concrete case where the added axis is needed to get the intended result - Whether the result copies data, and what that means for memory and for writes - Common mistakes with where the axis goes ### Follow-up Questions - How does `keepdims=True` on a reduction such as `mean` relate to adding an axis, and when would you use it instead? - How would you compute all pairwise Euclidean distances between two point sets with broadcasting, and what does that cost in memory? - How does `np.broadcast_to` differ from adding an axis, and what can you not do with its result?

Overview: Explain how to insert a length-1 axis into a NumPy array with np.newaxis or np.expand_dims and why that matters for broadcasting. Tests understanding of array shapes, NumPy's broadcasting rules, views versus copies, and the shape mistakes that cause silent bugs in data code.

PracHub logo
General
Nov 25, 2026
easyData ScientistOtherData Manipulation (SQL/Python)
0
0

How do you add a new axis to a NumPy array using np.newaxis or np.expand_dims, and why is this useful for broadcasting?

What a Strong Answer Covers Guidance

  • The syntax of both forms and the shape each one produces for a 1-D input
  • How NumPy's broadcasting rule decides whether two shapes are compatible
  • A concrete case where the added axis is needed to get the intended result
  • Whether the result copies data, and what that means for memory and for writes
  • Common mistakes with where the axis goes

Follow-up Questions Guidance

  • How does keepdims=True on a reduction such as mean relate to adding an axis, and when would you use it instead?
  • How would you compute all pairwise Euclidean distances between two point sets with broadcasting, and what does that cost in memory?
  • How does np.broadcast_to differ from adding an axis, and what can you not do with its result?