Python:NumPy Array Broadcasting

Sriparno08's avatar
Published Dec 24, 2024
Contribute to Docs

In NumPy, array broadcasting refers to the process of expanding the shape of a smaller array to match the shape of a larger array during arithmetic operations. This is helpful when there is a need to perform mathematical operations on two arrays of different shapes.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours

Example

The following example demonstrates the usage of array broadcasting:

import numpy as np
# Create an array of size (1 x 4)
arr1 = np.array([[11, 12, 13, 14]])
# Create an array of size (2 x 4)
arr2 = np.array([[21, 22, 23, 24], [25, 26, 27, 28]])
# Add the arrays
res = arr1 + arr2
# Print the result
print(res)

In the above example, the shape of the smaller array arr1 (1 x 4) is expanded to the shape of the larger array arr2 (2 x 4) during addition. After expansion, the array arr1 looks like [[11, 12, 13, 14], [11, 12, 13, 14]].

The above code produces the following output:

[[32 34 36 38]
[36 38 40 42]]

Codebyte Example

The following codebyte example demonstrates the usage of array broadcasting:

Code
Output

All contributors

Contribute to Docs

Learn Python:NumPy on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours