How to work efficiently with arrays, matrices, and numerical operations in Python
NumPy (Numerical Python) is the foundation of scientific computing in Python. It provides fast, memory‑efficient arrays and mathematical functions optimized in C. Libraries like pandas, SciPy, scikit‑learn, and many others rely on NumPy.
pip install numpy
NumPy arrays are more efficient than Python lists.
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr)
print(arr.dtype) # data type
print(arr.shape) # dimensions
np.zeros(5)
np.ones((2, 3))
np.arange(0, 10, 2)
np.linspace(0, 1, 5)
matrix = np.arange(9).reshape(3, 3)
print(matrix)
arr = np.array([1, 2, 3])
print(arr * 2)
print(arr + 5)
print(arr ** 2)
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6], [7, 8]])
print(a @ b) # matrix multiplication
print(np.dot(a, b)) # same result
arr = np.array([1, 2, 3, 4, 5])
print(arr.mean())
print(arr.sum())
print(arr.std())
arr = np.array([10, 20, 30, 40, 50])
print(arr[0]) # first element
print(arr[1:4]) # slice
arr = np.array([1, 2, 3, 4, 5])
mask = arr > 3
print(arr[mask]) # [4 5]
Now that you understand NumPy, you're ready to explore more advanced scientific tools in Lesson 29: Introduction to SciPy.
← Back to Lesson Index