Skip to main content
Practice

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

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.