Chapter 1 · Part 1

Setup & creating arrays

NumPy is the array library that all of scientific Python is built on — pandas, scikit-learn, PyTorch and the from-scratch neural net all sit on top of it. This is a hands-on course: every chapter ends with a puzzle you solve yourself before peeking. Best done with a Python shell open so you can poke at everything.

Install it

One dependency. Make a virtual environment and install NumPy:

terminal
python3 -m venv .venv
source .venv/bin/activate     # Windows: .venv\Scripts\Activate.ps1
pip install numpy

By convention, NumPy is always imported as np:

import numpy as np

The array — NumPy's one big idea

Everything in NumPy is an array: a grid of numbers, all the same type, that you operate on as a whole. You'll make them a handful of ways:

creating.py
import numpy as np

np.array([1, 2, 3, 4])        # from a Python list      -> [1 2 3 4]
np.arange(0, 10)              # a range (start, stop)   -> [0 1 2 3 4 5 6 7 8 9]
np.linspace(0, 1, 5)         # 5 evenly-spaced points  -> [0. 0.25 0.5 0.75 1.]
np.zeros((2, 3))             # a 2x3 grid of zeros
np.ones((2, 3))              # a 2x3 grid of ones
np.full((2, 2), 7)           # a 2x2 grid, all 7s
np.random.default_rng(0).random((2, 2))   # random numbers in [0, 1)

Every array knows its shape

An array carries its dimensions (shape), its rank (ndim), its element count (size), and its element type (dtype). You'll check these constantly:

shapes.py
a = np.array([[1, 2, 3],
            [4, 5, 6]])

print(a.shape)   # (2, 3) — 2 rows, 3 columns
print(a.ndim)    # 2      — a 2-D array
print(a.size)    # 6      — six elements total
print(a.dtype)   # int64  — the type of every element
🎯 Your turn
Create a 1-D array containing the even numbers from 0 to 20 (inclusive). Hint: np.arange takes a third argument — the step.

You can make arrays. Next, let's reach inside them.