NumPy Tutorial NumPy Statistics NumPy Resources
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

NumPy - broadcast() function

The NumPy broadcast() function produces an object that mimics broadcasting.


numpy.broadcast(in1, in2, …)


in1, in2, … Required. Specify the input parameters (array_like).

Return Value

Broadcast the input parameters against one another, and return an object that encapsulates the result.


In the example below, two arrays are added manually using broadcast() function.

import numpy as np

x = np.array([[1], [2], [3]])
y = np.array([4, 5, 6])

#using broadcast function to broadcast
#elements of x and y against one another 
b = np.broadcast(x, y)

#adding elements manually
out = np.empty(b.shape)
out.flat = [u+v for (u,v) in b]

#displaying results
print("Using broadcast() function:")

#comparing against built-in broadcasting
print("\nUsing built-in broadcasting:")

The output of the above code will be:

Using broadcast() function:
[[5. 6. 7.]
 [6. 7. 8.]
 [7. 8. 9.]]

Using built-in broadcasting:
[[5 6 7]
 [6 7 8]
 [7 8 9]]

❮ NumPy - Array Manipulation