NumPy (Numerical Python) is the backbone of scientific computing in Python. It provides the ndarray — a fast, memory-efficient multi-dimensional array.
1import numpy as np
2import time
3
4# Python list — slow
5data = list(range(1_000_000))
6start = time.time()
7result = [x * 2 for x in data]
8print(f"List: {time.time() - start:.3f}s") # ~0.08s
9
10# NumPy array — fast
11arr = np.arange(1_000_000)
12start = time.time()
13result = arr * 2 # vectorised — no Python loop!
14print(f"NumPy: {time.time() - start:.3f}s") # ~0.002s (40x faster)1import numpy as np
2
3# From a Python list
4a = np.array([1, 2, 3, 4, 5])
5
6# Ranges
7b = np.arange(0, 10, 2) # [0, 2, 4, 6, 8]
8c = np.linspace(0, 1, 5) # [0., 0.25, 0.5, 0.75, 1.]
9
10# Special arrays
11zeros = np.zeros((3, 4)) # 3×4 matrix of 0s
12ones = np.ones((2, 2)) # 2×2 matrix of 1s
13eye = np.eye(3) # 3×3 identity matrix
14random = np.random.randn(100) # 100 standard-normal samples1a = np.array([10, 20, 30, 40])
2b = np.array([ 1, 2, 3, 4])
3
4print(a + b) # [11, 22, 33, 44]
5print(a * b) # [10, 40, 90, 160]
6print(a / b) # [10., 10., 10., 10.]
7print(a ** 2) # [100, 400, 900, 1600]
8print(np.sqrt(a)) # [3.16, 4.47, 5.47, 6.32]1matrix = np.array([[1, 2, 3],
2 [4, 5, 6],
3 [7, 8, 9]])
4
5print(matrix[1, 2]) # 6 (row 1, col 2)
6print(matrix[:, 1]) # [2, 5, 8] (all rows, column 1)
7print(matrix[0:2, 0:2]) # top-left 2×2 submatrix
8
9# Boolean indexing
10data = np.array([15, 42, 7, 88, 23])
11print(data[data > 20]) # [42, 88, 23]1prices = np.array([299, 499, 999, 149, 799])
2
3print(prices.mean()) # 549.0
4print(prices.std()) # 312.7
5print(prices.min()) # 149
6print(prices.max()) # 999
7print(prices.sum()) # 2745
8print(np.median(prices))# 499.0