Array Arithmetic and Broadcasting
In NumPy, you can perform mathematical operations directly on arrays — no loops required.
This approach is known as element-wise computation, and it’s both efficient and concise.
Array Arithmetic
When two arrays have the same size, NumPy applies operations element by element.
a = np.array([1, 2, 3]) b = np.array([10, 20, 30]) print(a + b) # [11 22 33] print(a * b) # [10 40 90]
You can also subtract, divide, or raise to powers: a - b, a / b, a ** 2
Broadcasting
When arrays have different shapes, NumPy uses broadcasting to automatically align them.
Smaller arrays are conceptually “stretched” across the larger ones so the operation can be applied seamlessly.
a = np.array([1, 2, 3]) b = 10 print(a + b) # [11 12 13]
NumPy adds 10 to each element in a.
Broadcasting can also work between 2D and 1D arrays in many cases, which you will practice later.
Summary
- Use
+,-,*,/,**directly on arrays - Operations are applied element by element
- Broadcasting enables operations between arrays of different shapes
What is the purpose of broadcasting in NumPy?
To perform operations only on arrays of the same shape.
To convert arrays into a different data type.
To allow operations between arrays of different shapes by stretching smaller arrays.
To perform operations on single elements of an array.
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help