← Back to NumPy Course | Chapter 5: Array Manipulation | Lesson 7 of 7

squeeze/expand_dims

squeeze removes size-1 dimensions and expand_dims adds one back.

In this page:

  1. squeeze/expand_dims
Syntax
python
np.expand_dims(arr, axis)
np.squeeze(arr)

squeeze/expand_dims

expand_dims inserts a new axis of length 1 at the position you choose, which is often needed for broadcasting. squeeze removes axes of length 1. You can also add axes with np.newaxis.

Note: arr[:, np.newaxis] turns a 1-D array into a column.

Example: squeeze/expand_dims

python
import numpy as np

a = np.array([1, 2, 3])
col = np.expand_dims(a, axis=1)
print(col.shape)
print(a[np.newaxis, :].shape)
print(np.squeeze(col).shape)

# Output:
# (3, 1)
# (1, 3)
# (3,)
Related Topics
Common Mistakes
  1. Squeezing an axis whose length is not 1
  2. Losing track of which axis was added
  3. Using squeeze and unexpectedly collapsing a needed dimension
Chapter Summary
  • expand_dims adds a length-1 axis
  • squeeze removes length-1 axes
  • np.newaxis is a shorthand
  • Useful for broadcasting
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.