Lecture

Array Arithmetic and Broadcasting

In NumPy, you can perform math directly on arrays without writing loops.

This is called element-wise operations, and it is both fast and concise.


Array Arithmetic

When two arrays have the same size, NumPy applies operations element by element.

Array Arithmetic
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 are not the same shape, NumPy uses broadcasting to make them compatible.

This means smaller arrays are “stretched” so the operation can still work.

Broadcasting Example
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 allows arrays of different shapes to work together
Quiz
0 / 1

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