Module 4 · NumPy: Fast Maths on Arrays · Lesson 12 of 51

Arrays: lists that do maths

Why NumPy exists, creating arrays, shape and dtype, vectorised arithmetic instead of loops, and handy constructors such as arange, linspace and zeros.

In this lesson · about 35 minutes

  • Create 1-D and 2-D arrays and read their shape and dtype
  • Do arithmetic on whole arrays without loops
  • Explain why vectorised code is faster

Making arrays

import numpy as np
prices = np.array([4.5, 3.0, 4.75, 3.25])          # 1-D: shape (4,)
sales = np.array([[12, 15, 14, 18],
                  [8, 9, 11, 10],
                  [20, 22, 19, 25]])                # 2-D: shape (3, 4)
  • .shape is the size along each axis: (rows, columns) for 2-D. .ndim is the number of axes; .size the number of values.
  • .dtype is the type every value shares: int64, float64, bool. Mixing ints and floats gives floats.
  • Constructors: np.arange(0, 10, 2) → 0, 2, 4, 6, 8; np.linspace(0, 1, 5) → 5 evenly spaced values from 0 to 1; np.zeros(3), np.ones((2, 3)), np.full(4, 7).

Vectorised maths

Operations work element by element: qty * prices multiplies matching positions; prices + 0.25 adds to every value; np.sqrt, np.log, np.round apply to all values at once. Comparisons give arrays of True/False: prices > 4.

Lists behave differently: [1, 2] * 2 is [1, 2, 1, 2] (repeat), while np.array([1, 2]) * 2 is [2, 4] (maths).

Arrays in action

How much faster?

One million prices, raised 10% with a loop and with NumPy. Timings vary by device; the gap is what matters.

Exercise

Weekly revenue

Given price and sold (cups sold this week per drink), make revenue, an array of revenue per drink, and total, the sum of it. No loops.

Exercise

Convert temperatures

The weather feed gives Fahrenheit. Make celsius from fahrenheit with C = (F − 32) × 5 ⁄ 9, rounded to 1 decimal with np.round.

Check your understanding0 of 3 correct

Question 1

1.np.array([[1, 2, 3], [4, 5, 6]]).shape is…

Question 2

2.np.array([1, 2.5, 3]).dtype is…

Question 3

3.Why is prices * 1.1 faster than a loop?

Quiz score: 0 of 3

Exercises solved: 0 of 2

Tip: answer every quiz question correctly first.

Written by Noviq Academy in its own words. Kettle & Crumb and all its data are made up for teaching; any resemblance to a real business is a coincidence. Python runs in your browser with Pyodide, so results can differ slightly from your own computer. Power BI, Tableau and other product names belong to their owners. Read-aloud uses your device's built-in voices.