Broadcasting with NumPy Arrays in Python

Broadcasting is a NumPy feature that allows arithmetic operations between arrays of different shapes without explicitly reshaping them. When arrays have unequal dimensions, NumPy automatically adjusts the smaller array's shape by prepending dimensions of size 1, enabling element-wise operations.

Rules of Array Broadcasting

NumPy follows these rules when broadcasting arrays ?

  • Arrays with smaller ndim are prepended with dimensions of size 1 in their shape.

  • The output shape in each dimension is the maximum of the input sizes in that dimension.

  • An array can be used in calculation if its size in a particular dimension matches the output size or equals exactly 1.

  • If an array has a dimension size of 1, the first data entry in that dimension is used for all calculations along that dimension.

Broadcasting Example

Here's how broadcasting works when adding a 2D array with a 1D array ?

import numpy as np

a = np.array([[0.0, 0.0, 0.0],
              [10.0, 10.0, 10.0],
              [20.0, 20.0, 20.0],
              [30.0, 30.0, 30.0]])

b = np.array([1.0, 2.0, 3.0])

print('First array:')
print(a)
print('\nSecond array:')
print(b)
print('\nFirst Array + Second Array:')
print(a + b)
First array:
[[ 0.  0.  0.]
 [10. 10. 10.]
 [20. 20. 20.]
 [30. 30. 30.]]

Second array:
[1. 2. 3.]

First Array + Second Array:
[[ 1.  2.  3.]
 [11. 12. 13.]
 [21. 22. 23.]
 [31. 32. 33.]]

How Broadcasting Works

In the above example, array a has shape (4,3) and array b has shape (3,). NumPy broadcasts b to shape (4,3) by repeating it across the first dimension, allowing element-wise addition.

Array a (4,3): Array b (3,): Broadcast to (4,3) Broadcasted b: + Result (4,3):

Broadcasting with Different Shapes

Broadcasting works with various shape combinations. Here's an example with scalar and array ?

import numpy as np

# Scalar with array
arr = np.array([[1, 2, 3], [4, 5, 6]])
scalar = 10

print("Array shape:", arr.shape)
print("Scalar shape:", np.array(scalar).shape)
print("\nArray + Scalar:")
print(arr + scalar)
Array shape: (2, 3)
Scalar shape: ()

Array + Scalar:
[[11 12 13]
 [14 15 16]]

Conclusion

Broadcasting enables efficient element-wise operations between arrays of different shapes without creating copies. Understanding broadcasting rules helps write more efficient NumPy code and avoid shape-related errors in array operations.

Updated on: 2026-03-15T18:18:22+05:30

310 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements