NumPy is the foundation of the entire Python data stack — pandas, scikit-learn, SciPy and every deep-learning library are built on its arrays. It gives Python fast, memory-efficient numerical arrays and lets you express whole-array maths in a single line. This course assumes you're comfortable with the Python tutorial's lists and loops.
Why NumPy?
A Python list can hold anything, which makes it flexible but slow for numbers — each element is a full Python object. A NumPy array stores numbers in one contiguous block of memory and runs operations in optimised C. The result: array maths that's often 10–100× faster than a Python loop, and far less code:
import numpy as np# Python: a loopsquares = [x * x for x in range(1_000_000)]# NumPy: whole-array, no loop, much fastera = np.arange(1_000_000)squares = a ** 2
The ndarray
NumPy's core object is the ndarray (n-dimensional array): a grid of values, all of the same type. A 1-D array is a vector, 2-D is a matrix, and you can go higher:
a = np.array([1, 2, 3]) # 1-D (vector)b = np.array([[1, 2, 3], [4, 5, 6]]) # 2-D (matrix)a.ndim # 1 number of dimensionsb.ndim # 2b.shape # (2, 3) rows, columnsb.size # 6 total elements
Creating arrays
Beyond wrapping a list, NumPy has constructors for the arrays you need constantly:
np.zeros((2, 3)) # 2×3 of 0.0np.ones(5) # [1. 1. 1. 1. 1.]np.full((2, 2), 7) # filled with 7np.arange(0, 10, 2) # [0 2 4 6 8] (start, stop, step)np.linspace(0, 1, 5) # 5 evenly spaced points 0→1np.eye(3) # 3×3 identity matrixnp.random.rand(2, 3) # 2×3 of random floats in [0, 1)
dtype & shape
Every array has a single dtype (data type) and a shape. Because the type is uniform, NumPy can store and process the data efficiently:
a = np.array([1, 2, 3])a.dtype # dtype('int64')f = np.array([1, 2, 3], dtype=np.float64)f.dtype # dtype('float64')# Convert typea.astype(np.float32)
| Attribute | Meaning |
|---|---|
ndim | Number of dimensions |
shape | Size along each dimension, e.g. (2, 3) |
size | Total number of elements |
dtype | The type of every element (int64, float64…) |
Practice
Create a 3×4 array of zeros, a vector of 10 evenly-spaced numbers from 0 to 100, and a 5×5 identity matrix. Print each one's shape and dtype.
Key takeaways
- 01NumPy gives Python fast, memory-efficient numerical arrays — the base of the whole data stack.
- 02Import it as np by convention.
- 03The ndarray is a grid of same-typed values; ndim/shape/size describe it.
- 04Build arrays with zeros, ones, arange, linspace, eye and the random module — not just from lists.
- 05Every array has one dtype; a uniform type is what makes NumPy fast.
