What is broadcasting in Numpy?

It is impossible to carry out certain arithmetic operations if two arrays have different shapes. In this situation, Python provides you with a built-in numpy.array() broadcasting feature that broadcasts the smaller array across the larger array. Take a look at the example below:

svg viewer

Solution

As stated earlier, we will broadcast the smaller array across the larger array to perform this arithmetic operation.

svg viewer

Possible cases

One of the possible cases (shown above) that makes broadcasting possible is when two matrices have the same columns. However​, we have two more cases:

1 of 2

Code

# importing numpy library
import numpy as np
# MatA is a 3x3 matrix
MatA = np.array([[1,2,3],[4,5,6],[7,8,9]])
# MatB is also a 1x3 matrix
MatB = np.array([[1],[2],[3]])
# Arithmetic operation is possible because
# of broadcasting
print (MatA + MatB)

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved