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.

Python NumPy in Practice: The Code and Commands That Really Matter

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.

tl;dr
  • Introduction and Installation
  • Creation and inspection of arrays
  • Indexing slicing and fancy indexing
  • Vectorized operations
  • Broadcasting
~$ cat ./parcours.md # Python NumPy — 10 chapters
01
Introduction and Installation
→ Course presentation→ Install NumPy and the environment+ 1 more lessons
02
Creation and inspection of arrays
→ Create arrays→ Inspect shape, dtype, ndim+ 1 more lessons
03
Indexing slicing and fancy indexing
→ Basic indexing→ Multi-dimensional slicing+ 1 more lessons
04
Vectorized operations
→ Why vectorize?→ Element-wise operations+ 1 more lessons
05
Broadcasting
→ The rules of broadcasting→ Broadcasting in practice+ 1 more lessons
06
Linear algebra
→ Matrix product→ Transpose, inverse, determinant+ 1 more lessons
07
Statistics with NumPy
→ Mean, median, standard deviation→ Percentiles and quantiles+ 1 more lessons
08
Generation of random numbers
→ numpy.random.default_rng→ Statistical distributions+ 1 more lessons
🏁
Final project (+ 2 chapters along the way)
→ You leave with a concrete and demonstrable project

Create arrays

NOTEObjective — Discover all the array factories built into NumPy. Instead of writing Python lists by hand, learn to generate arrays of any shape with predefined values: zeros, ones, numeric ranges, identity matrices…

Learning objectives

TIPAt the end of this module — You will know how to choose the right factory for each need: initialize a weight matrix in a neural network, create a time axis for a plot, generate a mask filled with 1s, etc. These functions come up every day in data science.

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:

output
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)
WARNINGWatch the parentheses — For multiple dimensions, you must pass a tuple: np.zeros((3, 4)) and not np.zeros(3, 4). This is the #1 mistake beginners make.

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.

output
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):

output
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:

output
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)
WARNINGClassic pitfall — With a floating step (0.1, 0.01…), arange may produce a different number of elements than expected due to binary rounding errors. Prefer np.linspace for non-integer steps.

np.linspace: N regularly spaced points

np.linspace(start, stop, num) returns num points regularly spaced between start and stop, including both endpoints:

output
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

NOTEObjective — Learn to precisely access any element of an array: a single scalar, an entire row, an entire column, or a sub-array. This is one of the most used skills on a daily basis.

Learning objectives

TIPAt the end of this module — You will know how to extract a single element, a row or a column from a matrix, use negative indices to start from the end, and modify specific values with an assignment.

1D indexing: like a Python list

For a 1D array, indexing is identical to a Python list. The first element has index 0.

output
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.

output
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)
TIPTiparr[-1] is a very commonly used shortcut to access the last value, without having to compute arr[len(arr)-1].

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].

output
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
WARNINGarr[i, j] and not arr[i][j] — Both work, but arr[i, j] is faster and more idiomatic. arr[i][j] first creates row i (a sub-array) then takes element j from it; that's two operations instead of one.

Extract an entire row

With a single index, you retrieve the entire row:

output
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:

output
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())
WARNINGCommon errorbulletin[, 0] is not valid in Python. The comma needs a member on the left. Use bulletin[:, 0].

Modify a value by assignment

Indexing also works for writing. You can modify an element, an entire row or a column:

output
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

NOTEObjective — Set up a clean Python environment, install NumPy and verify that everything works. We will see the two main methods: pip (the standard manager) and conda (the Anaconda distribution, very popular in data science).

Learning objectives

TIPAt the end of this module — You will have Python installed, a virtual environment created, NumPy installed, Jupyter Notebook functional and confirmation that your setup is ready for the rest of the course.

Check Python on your machine

NumPy requires Python 3.9 or newer. To check your version, open a terminal and type:

output
# 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.

WARNINGWarning — Python 2 is obsolete — If your python command replies « Python 2.7… », use python3 or install a recent version. Modern NumPy no longer supports Python 2 since 2020.

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:

output
# 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.

output
# 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
TIPOur recommendation — If this is your first contact with data science, install Anaconda. You will get NumPy, Pandas, scikit-learn, Jupyter and everything you need in a single command, without fighting with C compilers or environment variables.

Verify that NumPy works

Once installed, open a Python interpreter (by typing python in the terminal) and type:

output
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)
go-further

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 Code

FAQ

How long does it take to learn Python NumPy?
With a structured progression (11 chapters, 35 short and practical lessons), you reach an operational level in a few weeks at 30 to 60 minutes per day. The important thing is to practice each concept immediately.
Are prerequisites required?
Basic computer knowledge is sufficient. If you know how to use a terminal and read simple code, you are ready.
Where to start concretely?
Reproduce the commands in this article, then follow the complete Python NumPy course: it chains the 35 lessons in order, with exercises and a final project.

📬 Want to receive this type of guide every week? Subscribe for free — real code, zero fluff.