What do np.squeeze and np.expand_dims do, and when would you use them?

Quick Overview

Asks what the NumPy functions squeeze and expand_dims do to an array's shape and when you would reach for each. It tests understanding of array dimensions, broadcasting rules, views versus copies, and preparing batch and channel axes for model inputs.

What do np.squeeze and np.expand_dims do, and when would you use them?

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: easy

Interview Round: Other

What do `np.squeeze` and `np.expand_dims` do, and when would you use them? ```hint Track the shapes Write down an array's shape before and after each call, then think about what broadcasting needs from two arrays whose shapes almost line up. ``` ### What a Strong Answer Covers - What each function does to an array's shape, with a concrete example - How the `axis` argument changes the behavior of each, including the error case - Whether the result copies the data or shares memory with the input - Practical situations that need each function, such as broadcasting and model inputs - The risk of removing axes without naming them ### Follow-up Questions - `X` has shape `(n, d)`. How do you subtract each row's mean without a loop, and what goes wrong if you skip the reshape when `n == d`? - What does `np.squeeze` return for an array of shape `(1, 1)`, and why might that break downstream code? - How do `reshape`, `np.newaxis` and `keepdims=True` compare with these two functions? - If you modify the result of `np.expand_dims`, does the original array change?

Overview: Asks what the NumPy functions squeeze and expand_dims do to an array's shape and when you would reach for each. It tests understanding of array dimensions, broadcasting rules, views versus copies, and preparing batch and channel axes for model inputs.

Nov 24, 2026
easyData ScientistOtherData Manipulation (SQL/Python)
0
0

What do np.squeeze and np.expand_dims do, and when would you use them?

What a Strong Answer Covers Guidance

  • What each function does to an array's shape, with a concrete example
  • How the axis argument changes the behavior of each, including the error case
  • Whether the result copies the data or shares memory with the input
  • Practical situations that need each function, such as broadcasting and model inputs
  • The risk of removing axes without naming them

Follow-up Questions Guidance

  • X has shape (n, d) . How do you subtract each row's mean without a loop, and what goes wrong if you skip the reshape when n == d ?
  • What does np.squeeze return for an array of shape (1, 1) , and why might that break downstream code?
  • How do reshape , np.newaxis and keepdims=True compare with these two functions?
  • If you modify the result of np.expand_dims , does the original array change?