What is the broadcast function in NumPy?

Overview

The broadcast() function in NumPy's Python library is used to create an object that mimics broadcasting.

Broadcasting in NumPy describes how NumPy treats arrays with different shapes by making use of arithmetic operations. To know more about broadcasting in NumPy, see this answer: What is broadcasting in NumPy?

Syntax

numpy.broadcast(in1, in2, ...)

Parameter value

The broadcast() function takes the parameter values, in1 in2 ..., which represents the input arrays.

Return value

The broadcast() function broadcasts the input arrays against each other and returns an object encapsulating the result.

Example

import numpy as np
# creating the input arrays
a = np.array([[1], [2], [3], [4]])
b = np.array([5, 6, 7, 8])
# calling the broadcast() function
np.broadcast(a,b)
# adding the two arrays using broadcasting
print(a + b)

Code explanation

  • Line 1: We import the numpymodule.

  • Line 3: We create an array a using the array() function.

  • Line 4: We create an array b using the array() function.

  • Line 7: We call the broadcast() function.

  • Line 10: We manually add the two arrays, a and b, using broadcasting. We print the result to the console.

Free Resources