Last updated

Array Math

Definition: NumPy applies maths to every element at once (vectorised), with no loop. Operations between two arrays work element by element.

Example 1 — element-wise arithmetic

import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([10, 20, 30, 40])
print(a + b)    # [11 22 33 44]
print(b - a)    # [ 9 18 27 36]
print(a * b)    # [10 40 90 160]
print(b / a)    # [10. 10. 10. 10.]

Example 2 — maths functions (ufuncs)

import numpy as np
a = np.array([1, 4, 9, 16])
print(np.sqrt(a))     # [1. 2. 3. 4.]
print(a ** 2)         # [1 16 81 256]
print(np.round(np.array([1.4, 2.6, 3.5])))

Example 3 — with a single number

import numpy as np
a = np.array([1, 2, 3])
print(a + 100)   # adds 100 to each
print(a * 10)    # multiplies each

💡 Tip: this is why NumPy is fast — one line replaces a whole loop, and the work happens in optimised C code under the hood.

Try it Yourself
Output

          
Ad · responsive