numpy
np.newaxis
Python
array manipulation
Python tutorial

How do I use np.newaxis?

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

np.newaxis is a NumPy indexing trick for inserting a size-1 dimension into an array. It does not change the underlying values. It changes the shape, which is exactly what you need when broadcasting or when converting a vector into an explicit row or column form.

What np.newaxis Actually Does

np.newaxis is just None used inside NumPy indexing syntax.

python
1import numpy as np
2
3a = np.array([10, 20, 30])
4print(a.shape)
5
6row = a[np.newaxis, :]
7col = a[:, np.newaxis]
8
9print(row.shape)
10print(col.shape)

The original shape is (3,). The row form becomes (1, 3). The column form becomes (3, 1).

That difference matters because (3,), (1, 3), and (3, 1) are not interchangeable in matrix-style operations.

Use It for Broadcasting

A classic use of np.newaxis is to make two arrays compatible for broadcasting.

python
1import numpy as np
2
3x = np.array([1, 2, 3])
4y = np.array([10, 20])
5
6diff = x[:, np.newaxis] - y[np.newaxis, :]
7print(diff)

x[:, np.newaxis] has shape (3, 1) and y[np.newaxis, :] has shape (1, 2), so NumPy can broadcast them into a (3, 2) result.

Without the inserted axes, the operation would fail.

Prepare Data for Machine Learning Code

Machine-learning pipelines often require explicit batch or channel dimensions. np.newaxis is an easy way to add them.

python
1import numpy as np
2
3image = np.random.rand(224, 224)
4batch = image[np.newaxis, :, :, np.newaxis]
5print(batch.shape)

That turns a grayscale image from height x width into batch x height x width x channel.

Compare It With reshape and expand_dims

There are other ways to add dimensions.

python
1import numpy as np
2
3v = np.array([1, 2, 3])
4
5print(v[:, np.newaxis].shape)
6print(v.reshape(3, 1).shape)
7print(np.expand_dims(v, axis=1).shape)

All three can produce the same result. The choice is mostly about readability:

  • 'np.newaxis is compact and natural in indexing expressions'
  • 'reshape is useful when you want to specify the whole target shape'
  • 'expand_dims is nice when the axis is computed dynamically'

Debug Shape Problems Early

When np.newaxis code goes wrong, the failure is usually not about values. It is about shapes. Print shapes before and after the operation.

python
1import numpy as np
2
3a = np.arange(5)
4print("original:", a.shape)
5print("row:", a[np.newaxis, :].shape)
6print("col:", a[:, np.newaxis].shape)

That habit prevents most broadcasting bugs from turning into confusing downstream errors.

Read np.newaxis as Shape Documentation

One reason experienced NumPy users like np.newaxis is that it makes intent visible inside the expression itself. A reader can often tell immediately whether you meant “treat this as a column” or “add a batch axis here.”

That is valuable because array code is often hard to read. Clear shape intent is part of correctness, not just style.

Remember That It Usually Returns a View

np.newaxis normally changes only how the array is viewed. That means it is cheap, but it also means mutations through the view still affect the same underlying data.

Common Pitfalls

The biggest mistake is treating (n,) and (n, 1) as if they were the same. They are not.

Another issue is inserting the new axis in the wrong position and getting a valid but incorrect broadcast result.

A third problem is writing dense one-liners with several inserted axes and no shape checks, which makes debugging much harder than it needs to be.

Summary

  • 'np.newaxis inserts a size-1 dimension into an array.'
  • It changes shape, not values.
  • It is especially useful for row-versus-column conversion and broadcasting.
  • 'reshape and expand_dims can do similar jobs with different readability tradeoffs.'
  • Print shapes when debugging np.newaxis code so broadcasting behavior stays explicit.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.