Python NumPy in Practice: The Code and Commands That Really Matter
Python NumPy: The Essentials in One Article — Real Code, Diagrams and Concrete Steps, Excerpts from a 35-Lesson Course.
No endless theory here: open the terminal and practice. Here is the essentials of Python NumPy, extracted directly from a complete 35-lesson course — with real code you can copy-paste right now.
- Introduction and Installation
- Creation and inspection of arrays
- Indexing slicing and fancy indexing
- Vectorized operations
- Broadcasting
Create arrays
Learning objectives
Why not always np.array()?
You could always write np.array([0,0,0,0,0,0,0,0,0,0]). But now imagine you need an array of 1 000 000 zeros: impossible to type by hand.
Fortunately, NumPy provides specialized factories for these recurring cases. They are faster, more readable and safer than a Python loop.
np.zeros: an array of zeros
The #1 tool for initializing an array. Pass the desired shape as argument:
import numpy as np # Vector of 5 zeros a = np.zeros(5) print(a) # [0. 0. 0. 0. 0.] # 3 x 4 matrix of zeros b = np.zeros((3, 4)) print(b) # [[0. 0. 0. 0.] # [0. 0. 0. 0.] # [0. 0. 0. 0.]] # 2 x 3 x 4 cube (a 3D tensor!) c = np.zeros((2, 3, 4)) print(c.shape) # (2, 3, 4)
np.ones: an array of ones
Identical to zeros, but filled with 1. Very useful as a mask, or as a starting point for weight matrices.
import numpy as np # Weight vector initialized to 1 poids = np.ones(10) print(poids) # [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] # 3 x 3 square matrix of ones M = np.ones((3, 3), dtype=int) print(M) # [[1 1 1] # [1 1 1] # [1 1 1]]
Note the dtype=int parameter: by default, zeros and ones produce float64. If you want integers, request it explicitly.
np.full: fill with any value
When you want to fill with a value other than 0 or 1, use np.full(shape, value):
import numpy as np # 2x3 matrix filled with 7 sept = np.full((2, 3), 7) print(sept) # [[7 7 7] # [7 7 7]] # Array of NaN (missing value) nan_arr = np.full(5, np.nan) print(nan_arr) # [nan nan nan nan nan]
Common practical case: initialize an array of results to NaN, then fill cell by cell as the calculation progresses.
np.arange: the NumPy version of « range »
np.arange(start, stop, step) is the NumPy equivalent of Python's range function, but it returns an ndarray:
import numpy as np # 0, 1, 2, ..., 9 (stop is excluded) a = np.arange(10) print(a) # [0 1 2 3 4 5 6 7 8 9] # From 5 to 20 (excluded), step of 2 b = np.arange(5, 20, 2) print(b) # [ 5 7 9 11 13 15 17 19] # With a floating step: possible but avoid c = np.arange(0, 1, 0.1) print(c) # [0. 0.1 0.2 ... 0.9] (but caution, see warning)
np.linspace: N regularly spaced points
np.linspace(start, stop, num) returns num points regularly spaced between start and stop, including both endpoints:
import numpy as np # 11 points from 0 to 1 inclusive a = np.linspace(0, 1, 11) print(a) # [0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ] # 5 points between -pi and +pi (ideal for plotting sin/cos) x = np.linspace(-np.pi, np.pi, 5) print(x) # [-3.14 -1.57 0. 1.57 3.14] # 1000 points for a smooth plot t = np.linspace(0, 10, 1000)
linspace is indispensable for plotting mathematical curves with Matplotlib. It is the #1 tool for creating continuous axes.
Basic indexing
Learning objectives
1D indexing: like a Python list
For a 1D array, indexing is identical to a Python list. The first element has index 0.
import numpy as np notes = np.array([12, 15, 17, 9, 18, 14]) print(notes[0]) # 12 (first grade) print(notes[2]) # 17 (third grade) print(notes[5]) # 14 (last grade)
The returned type is a NumPy scalar, not an array. You can use it like a normal Python number.
Negative indices: from the end
As in Python, -1 designates the last element, -2 the second-to-last, etc.
import numpy as np notes = np.array([12, 15, 17, 9, 18, 14]) print(notes[-1]) # 14 (last) print(notes[-2]) # 18 (second-to-last) print(notes[-6]) # 12 (the first, from the end)
2D indexing: row and column
For a matrix, you need two indices: arr[i, j]. This is the NumPy convention, much clearer than Python's arr[i][j].
import numpy as np bulletin = np.array([ [14, 15, 12], # student 0 [18, 11, 17], # student 1 [9, 10, 8], # student 2 [16, 19, 14], # student 3 ]) # Grade of student 1 in subject 2 (English) print(bulletin[1, 2]) # 17 # Student 3 in math (column 0) print(bulletin[3, 0]) # 16
Extract an entire row
With a single index, you retrieve the entire row:
import numpy as np bulletin = np.array([ [14, 15, 12], [18, 11, 17], [9, 10, 8], [16, 19, 14], ]) eleve1 = bulletin[1] print(eleve1) # [18 11 17] print(eleve1.shape) # (3,) # Explicit equivalent with slice: print(bulletin[1, :]) # [18 11 17]
Both syntaxes bulletin[1] and bulletin[1, :] are equivalent. The form with : is more explicit: « row 1, all columns ».
Extract an entire column
For the column, you MUST use the two-dimensional syntax:
import numpy as np bulletin = np.array([ [14, 15, 12], [18, 11, 17], [9, 10, 8], [16, 19, 14], ]) # All math grades (column 0) math = bulletin[:, 0] print(math) # [14 18 9 16] # Average per subject print("Math average:", bulletin[:, 0].mean()) print("French average:", bulletin[:, 1].mean()) print("English average:", bulletin[:, 2].mean())
Modify a value by assignment
Indexing also works for writing. You can modify an element, an entire row or a column:
import numpy as np bulletin = np.array([ [14, 15, 12], [18, 11, 17], [9, 10, 8], ]) # Modify a single cell bulletin[0, 1] = 16 print(bulletin[0]) # [14 16 12] # Replace entire row 2 bulletin[2] = [11, 12, 13] print(bulletin) # [[14 16 12] # [18 11 17] # [11 12 13]] # Set an entire column to zero bulletin[:, 2] = 0 print(bulletin) # [[14 16 0] # [18 11 0] # [11 12 0]]
Install NumPy and the environment
Learning objectives
Check Python on your machine
NumPy requires Python 3.9 or newer. To check your version, open a terminal and type:
# Windows (PowerShell or cmd) python --version # macOS / Linux python3 --version # Expected output (example): # Python 3.12.4
If Python is not installed, download it from the official site python.org/downloads. On Windows, be sure to check the « Add Python to PATH » box during installation.
Why a virtual environment?
A virtual environment is an isolated folder that contains its own copy of Python and its own libraries. It allows you to have one project with NumPy 1.26 and another with NumPy 2.0 without them conflicting.
Without virtual environment
With virtual environment
Method 1: pip + venv (standard Python)
This is the official method, lightweight and integrated with Python. Create a project folder, then open a terminal inside it:
# 1. Create a virtual environment named "venv" python -m venv venv # 2. Activate the environment # Windows PowerShell: venv\Scripts\Activate.ps1 # macOS / Linux: source venv/bin/activate # 3. Install NumPy pip install numpy # 4. (Optional) Also install Jupyter and matplotlib pip install jupyter matplotlib pillow
Once activated, your prompt shows (venv) in front. This is the sign that you are working in your isolated bubble.
Method 2: Anaconda / Miniconda
Anaconda is a scientific distribution of Python that ships already installed the main data science libraries: NumPy, Pandas, scikit-learn, Jupyter, etc. It is ultra-convenient for beginners.
# 1. Download Anaconda from anaconda.com/download # 2. Run the graphical installer # 3. Once installed, open the Anaconda Prompt # Check the version of NumPy shipped conda list numpy # Create an environment dedicated to the course conda create -n cours-numpy python=3.12 numpy jupyter matplotlib pillow # Activate it conda activate cours-numpy
If you only want the strict minimum, choose Miniconda which is a lightweight version (~50 MB) instead of Anaconda (~3 GB).
pip vs conda: which to choose?
| Criterion | pip + venv | conda |
|---|---|---|
| Target audience | Python developers | Data scientists, students |
| Initial size | Very light | Heavier (especially Anaconda) |
| Pre-installed libraries | None | Already the entire data science stack |
| Installation speed | Very fast for NumPy | Slower but resolves dependencies better |
| Complete C libraries | Sometimes complicated (OpenCV, etc.) | Always functional |
| Course recommendation | OK if you know Python | Recommended for beginners |
Verify that NumPy works
Once installed, open a Python interpreter (by typing python in the terminal) and type:
import numpy as np # Check the version print(np.__version__) # Expected output (for example): 2.1.0 # Create a first array a = np.array([1, 2, 3, 4, 5]) print(a) print("Type:", type(a)) print("Shape:", a.shape) print("Element type:", a.dtype)
This article covers the most useful excerpts — the complete Python NumPy course (11 chapters, 35 lessons, corrected exercises and final project) takes you all the way.
./access-the-complete-course free course: Mastering Claude CodeFAQ
How long does it take to learn Python NumPy?
Are prerequisites required?
Where to start concretely?
📬 Want to receive this type of guide every week? Subscribe for free — real code, zero fluff.