Element-Wise Arithmetic
Add, subtract, multiply, and divide arrays element-by-element and understand how NumPy avoids explicit Python loops.
The Problem with Python Loops
Adding lists in pure Python needs a slow loop. NumPy does it in fast C instead — often 10 to 100 times quicker. This trick is called vectorisation. ⚡
# Python list approach -- slow
a = [1, 2, 3, 4]
b = [10, 20, 30, 40]
result = [x + y for x, y in zip(a, b)]
print(result) # [11, 22, 33, 44]
# NumPy approach -- fast
import numpy as np
na, nb = np.array(a), np.array(b)
print(na + nb) # [11 22 33 44]Addition and Subtraction
The + and - operators work element by element on arrays of the same shape, pairing up matching positions in one quick pass.
import numpy as np
a = np.array([10, 20, 30])
b = np.array([1, 2, 3])
print(a + b) # [11 22 33]
print(a - b) # [ 9 18 27]All lessons in this course
- Creating NumPy Arrays
- Array Attributes and Inspection
- Element-Wise Arithmetic
- Array Slicing and Indexing