NumPy for Numerical Computing
Published by Brayan K
NumPy is the foundation of scientific Python. Its ndarray stores numbers in a fast, contiguous, typed block and runs vectorized operations in compiled C — turning slow Python loops into fast array math used by pandas, scikit-learn, and PyTorch.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Give each dimension a meaning before doing arithmetic
A Python list of rows does not tell NumPy what those rows mean. For this report, each row is a shop and each column is a day. We will calculate shop totals, compare daily targets and reject malformed inputs. The shape is part of the contract, not just a number printed while debugging.
An ndarray describes typed data with a shape and strides: the steps through its underlying memory. A newly created array may be contiguous, but a sliced view can skip elements and need not be contiguous. Array operations do not require every view to occupy one uninterrupted sequence of adjacent values.
import numpy as np
sales = np.array([[3, 5, 4], [2, 6, 7]], dtype=np.int64)
print(sales.shape, sales.ndim, sales.size)
print(sales[0, 2])
print(sales.sum(axis=1).tolist())
print(sales.sum(axis=0).tolist())
# ✅ Expected output:
# (2, 3) 2 6
# 4
# [12, 15]
# [5, 11, 11]There are two shops and three days. Reducing axis 1 removes the day dimension, leaving a total for each shop. Reducing axis 0 removes the shop dimension, leaving a total for each day. A bare sum removes every dimension. Draw the table and name the dimension being removed before choosing an axis.
The programs use NumPy’s array API and run with native NumPy 2.4.6; the browser has an older NumPy release, so each browser example is checked there too. For the wider array-construction catalog, see Creating Arrays (array, zeros, arange, linspace). This lesson owns a Python-to-array reporting boundary and its failure cases.
An array changes what multiplication means
import numpy as np
counts = [2, 4, 6]
values = np.array(counts, dtype=np.int64)
print(counts * 2)
print((values * 2).tolist())
print((values + 1).tolist())
print((values / 2).tolist())
# ✅ Expected output:
# [2, 4, 6, 2, 4, 6]
# [4, 8, 12]
# [3, 5, 7]
# [1.0, 2.0, 3.0]A list repeats when multiplied by an integer. An ndarray applies this arithmetic to each element, and division produces floating values here. Vectorized syntax expresses array operations; it does not make every possible task faster. Avoid timing claims unless you measure a representative workload separately.
import numpy as np
small = np.array([120], dtype=np.int8)
wide = small.astype(np.int64)
print((small + np.array([10], dtype=np.int8)).tolist())
print((wide + 10).tolist())
print(wide.dtype == np.dtype("int64"))
# ✅ Expected output:
# [-126]
# [130]
# TrueThe small integer wraps because its result cannot fit in eight signed bits. Widen before the operation when the result needs a larger range; widening afterward cannot recover the lost value. Array Data Types (dtypes) owns promotion and representation details.
Compatible broadcasting can still mean the wrong calculation
import numpy as np
sales = np.array([[3, 5, 4], [2, 6, 7]], dtype=np.int64)
daily_target = np.array([3, 4, 5], dtype=np.int64)
print((sales - daily_target).tolist())
print((sales >= daily_target).tolist())
shop_bonus = np.array([1, 2], dtype=np.int64)
print((sales + shop_bonus[:, None]).tolist())
# ✅ Expected output:
# [[0, 1, -1], [-1, 2, 2]]
# [[True, True, False], [False, True, True]]
# [[4, 6, 5], [4, 8, 9]]The three daily targets align with the three columns. The two shop bonuses need a column shape, made by adding a dimension with [:, None]. NumPy matches dimensions from the right; matching sizes or a size of one can broadcast. A matching shape is necessary but does not prove that labels are aligned. Reorder input explicitly if the shops or days arrive in a different order.
import numpy as np
sales = np.array([[3, 5, 4], [2, 6, 7]], dtype=np.int64)
shop_bonus = np.array([1, 2], dtype=np.int64)
print(sales + shop_bonus)
# ✅ Expected error:
# ValueError: operands could not be broadcast together with shapes (2,3) (2,)This error is useful: a length-two vector cannot align with the length-three final dimension. Do not reshape at random until it runs. Decide which dimension the values belong to, then express that relationship. The complete rules and higher-dimensional cases belong to Broadcasting Explained.
A basic slice can modify its parent
import numpy as np
sales = np.array([[3, 5, 4], [2, 6, 7]], dtype=np.int64)
first_day = sales[:, 0]
first_day[0] = 99
print(sales.tolist())
print(np.shares_memory(sales, first_day))
independent = sales[:, 1].copy()
independent[0] = -1
print(sales[:, 1].tolist())
print(np.shares_memory(sales, independent))
# ✅ Expected output:
# [[99, 5, 4], [2, 6, 7]]
# True
# [5, 6]
# FalseBasic slicing returns a view into the same underlying data. Copy before making an independent editable subset. Passing an array through np.asarray also does not promise a fresh allocation; preserve caller-owned data by avoiding mutation or by requesting a copy.
import numpy as np
values = np.array([2, 7, 4, 9], dtype=np.int64)
chosen = values[values >= 5]
chosen[0] = 100
print(values.tolist())
values[values >= 5] = 0
print(values.tolist())
# ✅ Expected output:
# [2, 7, 4, 9]
# [2, 0, 4, 0]Boolean indexing produces a new array when reading. Assigning through that index targets the original array. These are different operations even though both contain the same mask. Indexing and Slicing Arrays and Boolean & Fancy Indexing own the indexing catalog.
Ask a precise question of a boolean array
import numpy as np
values = np.array([2, 7, 4])
if values > 3:
print("large")
# ✅ Expected error:
# ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()import numpy as np
values = np.array([2, 7, 4])
mask = (values > 3) & (values < 7)
print(mask.tolist())
print(values[mask].tolist())
print(bool((values > 3).any()))
print(bool((values > 3).all()))
# ✅ Expected output:
# [False, False, True]
# [4]
# True
# FalseParenthesize each comparison and use & for elementwise conjunction. Python and asks for a single truth value and does not combine array masks. any asks whether at least one value qualifies; all asks whether every value qualifies. Neither validates a missing dimension or an empty dataset for you.
Make the report reject ambiguous data
import numpy as np
def daily_totals(rows):
data = np.asarray(rows, dtype=np.float64)
if data.ndim != 2 or data.shape[0] == 0 or data.shape[1] != 3:
raise ValueError("need at least one shop and exactly three days")
if not np.isfinite(data).all():
raise ValueError("sales must be finite")
if (data < 0).any():
raise ValueError("sales must not be negative")
return data.sum(axis=0)
print(daily_totals([[3, 5, 4], [2, 6, 7]]).tolist())
for bad in [[], [[1, 2]], [[1, float("nan"), 3]], [[1, -2, 3]]]:
try:
daily_totals(bad)
except ValueError as problem:
print(str(problem))
# ✅ Expected output:
# [5.0, 11.0, 11.0]
# need at least one shop and exactly three days
# need at least one shop and exactly three days
# sales must be finite
# sales must not be negativeConverting to float is a policy: compatible numeric strings would also convert. This boundary deliberately accepts real-valued sales, not exact currency arithmetic, and rejects non-finite data instead of silently treating it as zero. For money, choose integer minor units or an appropriate decimal design. A ragged row sequence can fail during array construction itself; callers should handle that ValueError too.
Complete a per-shop target report
Sum each shop’s three days, compare with its target, then convert the result to ordinary Python values for a caller. Fill in the reduction axis and the conversion method.
import numpy as np
sales = np.array([[3, 5, 4], [2, 6, 7]], dtype=np.int64)
targets = np.array([13, 14], dtype=np.int64)
totals = sales.sum(axis=___)
print(totals.tolist())
print((totals >= targets).___())
# 👉 replace ___ with 1
# 👉 replace ___ with tolist
# ✅ Expected output:
# [12, 15]
# [False, True]Build a report that cannot alter the source table
Write shop_report(rows, targets). Require a nonempty two-dimensional table with exactly three days, one target per shop, and finite nonnegative values. Return ordinary Python lists of totals and target flags. Show a successful call, an invalid target shape, and that the caller’s array has not changed. No operation should edit the input.
import numpy as np
def shop_report(rows, targets):
data = np.asarray(rows, dtype=np.float64)
goal = np.asarray(targets, dtype=np.float64)
if data.ndim != 2 or data.shape[0] == 0 or data.shape[1] != 3:
raise ValueError("need shops by three days")
if goal.shape != (data.shape[0],):
raise ValueError("need one target per shop")
if not np.isfinite(data).all() or not np.isfinite(goal).all():
raise ValueError("values must be finite")
if (data < 0).any() or (goal < 0).any():
raise ValueError("values must not be negative")
totals = data.sum(axis=1)
return {"totals": totals.tolist(), "met": (totals >= goal).tolist()}
source = np.array([[3, 5, 4], [2, 6, 7]], dtype=np.int64)
before = source.copy()
print(shop_report(source, [13, 14]))
print(np.array_equal(source, before))
try:
shop_report(source, [[13], [14]])
except ValueError as problem:
print(str(problem))
# ✅ Expected output:
# {'totals': [12.0, 15.0], 'met': [False, True]}
# True
# need one target per shopThe two-dimensional target column is rejected even though it might participate in some broadcast. Its meaning is wrong for the one-dimensional totals contract. This is the difference between a numerical library accepting an expression and an application accepting a valid request.
Practice quiz
What does this program print? import numpy as np a = np.array([[1, 2, 3], [4, 5, 6]]) print(a.sum(axis=1).tolist())
- [6, 15]
- [5, 7, 9]
- 21
- [1, 2, 3, 4, 5, 6]
Answer: [6, 15]. Axis 1 removes columns, leaving one total for each row.
What does this program print? import numpy as np a = np.array([2, 4]) b = a[:] b[0] = 9 print(a.tolist())
- [2, 4]
- [9, 4]
- [9, 9]
- ValueError
Answer: [9, 4]. Basic slicing gives a view sharing the original data.
What does this program print? import numpy as np a = np.array([2, 7, 4]) b = a[a > 3] b[0] = 0 print(a.tolist())
- [2, 0, 4]
- [0, 4]
- [2, 7, 4]
- [0, 0, 0]
Answer: [2, 7, 4]. Reading with a boolean mask creates an independent result.
A table has shape (4, 3). What shape expresses one bonus per row for broadcasting?
- (3,)
- (4,)
- (1, 4)
- (4, 1)
Answer: (4, 1). A trailing size-one dimension can expand across the three columns.
What does this program print? import numpy as np a = np.array([1, 4, 8]) print(((a > 2) & (a < 7)).tolist())
- [False, True, False]
- [True, True, True]
- [False, False, True]
- ValueError
Answer: [False, True, False]. Both comparisons must be true for each selected element.
Why validate shape before calculating a report?
- Every compatible shape has the same meaning
- Broadcasting compatibility does not verify the data contract
- NumPy cannot calculate totals
- Shape validation makes floats exact
Answer: Broadcasting compatibility does not verify the data contract. Correct dimension sizes and meanings are application responsibilities.
When should you widen a fixed-width integer array to prevent overflow?
- Only after it wraps
- Only when printing
- Before the arithmetic that may exceed its range
- Never
Answer: Before the arithmetic that may exceed its range. Casting after overflow preserves the already-wrong wrapped result.
Why return .tolist() at a plain-data boundary?
- It validates all business rules
- It sorts the values
- It changes the original array
- It converts the array result into ordinary Python lists and scalars
Answer: It converts the array result into ordinary Python lists and scalars. This keeps an array-specific object out of callers expecting plain data.
Continue this course
- Previous: Data Validation with Pydantic
- Next: Data Visualization with Matplotlib — Line, scatter, bar and histogram plots with the pyplot and object-oriented APIs
- Quick reference: Python cheat sheet