Arrays
Storing a Sequence
- A Python
liststores pointers to individual objects scattered across memory. - Each object carries its own type information, reference count, and value. A Python list containing
[10, "hello", 3.14]is made up of multiple C objects in memory:
- Iterating through a list means following each pointer to a different memory location
- An array stores raw values in a single contiguous block of memory.
- This means it has no per-element type headers or scattered objects
Ten million float64 values in an array uses 80 MB (8 bytes each). A Python list of the same type uses roughly 320 MB: 8 bytes for each pointer plus about 24 bytes for each separate float object.
Python's standard library includes array.array, which stores values contiguously, but it lacks support for multi-dimensional data and vectorised operations.
NumPy
- NumPy (Numerical Python) is a library for numerical computing implemented in C
- Developed in 2005 by Travis Oliphant, combining the earlier Numeric and Numarray projects
- Provides the ndarray: a typed, contiguous, multi-dimensional array
- Acts as a common data format across the scientific Python ecosystem (SciPy, pandas, scikit-learn)
- It uses compiled loops, contiguous typed memory, and CPU vector instructions (SIMD)
ndarray
NumPy arrays are created passing a sequence to np.array():
import numpy as np
# 1D array from a list
temperatures = np.array([18.3, 19.1, 17.6, 20.4])
print(type(temperatures)) # <class 'numpy.ndarray'>
print(temperatures.dtype) # float64
print(temperatures.shape) # (4,)
Nested lists become multi-dimensional arrays:
# 2D array from nested lists
grid = np.array([
[18.3, 19.1, 17.6],
[20.4, 18.9, 21.0]
])
print(grid.shape) # (2, 3)
print(grid.dtype) # float64
print(grid[1, 2]) # 21.0
A shape of (2, 3) is the same as a list containing two lists of 3 elements, but all values are stored in one contiguous block with a uniform type.
Terminology
- A vector is a 1-dimensional array (a sequence of values)
- A matrix is a 2-dimensional array (rows and columns)
- A tensor has three or more dimensions
Data Types
Every array holds elements of a single type specified by its dtype.
a = np.array([1, 2, 3])
a.dtype # dtype('int64')
np.array([1.5, 2, 3]).dtype # dtype('float64')
The type can be specified when creating an array or change changed with the astype function.
np.arange(5, dtype=np.float64)
# array([0., 1., 2., 3., 4.])
b = a.astype(np.float64) # astype always returns a copy
# array([1., 2., 3.])
np.array([1.9, -1.9]).astype(int)
# array([ 1, -1]) # truncates, does not round
Common types
The default int64 and float64 can safely handle most numbers, NumPy provides a number of scalars:
| dtype | meaning |
|---|---|
int8 to int64 |
signed integers of that many bits |
uint8 … |
unsigned (non-negative) integers |
float32, float64 |
floating point numbers |
bool |
True / False |
<U … |
fixed-width strings |
Array Constructors
NumPy provides several ways to create arrays without writing out values by hand:
# Array of zeros
np.zeros(5)
# array([0., 0., 0., 0., 0.])
# Array of ones, with a specified shape
np.ones((3, 2))
# array([[1., 1.],
# [1., 1.],
# [1., 1.]])
# Range of integers (like Python's range)
np.arange(6)
# array([0, 1, 2, 3, 4, 5])
# Range with a step
np.arange(0, 10, 2)
# array([0, 2, 4, 6, 8])
Shape and Strides
A NumPy array is a single contiguous block of memory combined with metadata that describes how to interpret it. The two most important pieces of metadata are the shape and the strides.
- The shape defines the dimensions of the array
- The strides define how many bytes to jump in memory to move one step along each dimension
a = np.arange(12)
print(a) # [ 0 1 2 3 4 5 6 7 8 9 10 11]
print(a.dtype) # int64
print(a.shape) # (12,)
print(a.itemsize) # 8 bytes per element
print(a.strides) # (8)
When we reshape this into a 4x3 matrix, no data is copied. NumPy simply changes the shape and strides:
x = a.reshape(4, 3)
print(x)
# [[ 0 1 2]
# [ 3 4 5]
# [ 6 7 8]
# [ 9 10 11]]
print(x.shape) # (4, 3)
print(x.strides) # (24, 8)
The strides (24, 8) mean: to move to the next row, jump 24 bytes (3 elements of 4 bytes each). A 64 bit integer uses 8 bytes of memory, moving to the next column requires a jump of 8 bytes (1 element).
The same twelve values can be viewed as (4, 3), (6, 2), (2, 6), or (12,) without copying anything. NumPy just recalculates the strides each time.
Reshape, Transpose, Flatten
Reshape
reshape changes how the same block of memory is interpreted by changing the strides. No data is copied.
a = np.arange(6) # array([0, 1, 2, 3, 4, 5])
a = a.reshape(2, 3)
# array([[0, 1, 2],
# [3, 4, 5]])
Setting -1 as one of the shape dimensions lets NumPy infer its length from the remaining elements
np.arange(6).reshape(3, -1)
# [[0 1]
# [2 3]
# [4 5]]
Transpose
.T (shorthand for .transpose()) transposes by swapping rows and columns:
a.T
# array([[0, 3],
# [1, 4],
# [2, 5]])
Flatten
flatten returns a 1D copy of the array:
a.flatten()
# array([0, 1, 2, 3, 4, 5])
Note the difference: reshape and transpose produce views (no copy), while flatten produces a new array.
Vector Operations
Arithmetic operators are vectorised so that they work on each element, and avoids having to write a for loop.
Array and Scalar
A scalar is a single value that is applied to every element in an array during a vector operation. Combining an array with a scalar value applies the operation to every element
a = np.array([3, 4, 5])
a * 3 # array([ 9, 12, 15])
a - 1 # array([2, 3, 4])
a / 2 # array([1.5, 2. , 2.5])
a ** 2 # array([ 9, 16, 25])
Array and Array
Combining two arrays of the same shape operates on matching elements. Arrays of compatible shapes can combined using broadcasting, if shapes are incompatible NumPy raises a ValueError.
a = np.arange(8).reshape(4, 2)
b = np.ones(8, dtype=int).reshape(4, 2)
a + b
Broadcasting
Broadcasting allows NumPy to perform operations on arrays with different shapes.
- Shapes are compared right to left: two dimensions are compatible if they are equal, or if one of them is 1.
- A dimension of size 1 is stretched to match the other.
- If one shape is shorter, it is padded with 1s on the left.
A 1D array whose length matches the number of columns is applied to every row:
a = np.array([[0, 0, 0],
[0, 0, 0]]) # shape (2, 3)
offsets = np.array([1, 2, 3]) # shape (3,)
a + offsets
# (2, 3) + (3,) -> (2, 3)
Broadcasting also works when both arrays are stretched:
a = np.array([0, 3, 6, 9]).reshape(4, 1)
a.shape # (4, 1)
b = np.array([1, 2])
b.shape # (2,)
a * b
# Shape: (4, 2)
Slicing and Indexing
Slicing a 1D array works like slicing a list:
a = np.arange(5) # array([0, 1, 2, 3, 4])
a[1:3] # array([1, 2])
For matrices, comma-separated indices can be used:
grid = np.array([[10, 20, 30],
[40, 50, 60]])
grid[1, 2] # 60 row 1, column 2
grid[0] # array([10, 20, 30]) entire row 0
grid[:, 1] # array([20, 50]) all rows, column 1
The : means all elements along this axis. Slices can be combined across axes:
grid[:, 1:] # array([[20, 30], rows 0-1, columns 1-2
# [50, 60]])
Views vs Copies
Slicing a NumPy array returns a view. Views are used for memory efficiency: reshaping and slicing can take place without duplicating data.
Modifying the view modifies the original:
a = np.arange(5) # array([0, 1, 2, 3, 4])
b = a[1:4] # array([1, 2, 3])
b[0] = 99
print(a) # array([ 0, 99, 2, 3, 4])
This is different from Python lists, where slicing creates a new list:
lst = [0, 1, 2, 3, 4]
sub = lst[1:4] # [1, 2, 3]
sub[0] = 99
print(lst) # [0, 1, 2, 3, 4] unchanged
Copies of the data can be made with the .copy() method
b = a[1:4].copy()
b[0] = 99 # only b is modified
Universal Functions
NumPy provides optimised element-wise functions called universal functions (ufuncs). These operate on every element without requiring a Python loop:
a = np.array([1, 4, 9, 16, 25])
np.sqrt(a)
# array([1., 2., 3., 4., 5.])
np.square(a)
# array([ 1, 16, 81, 256, 625])
np.exp(np.array([0, 1, 2]))
# array([1. , 2.71828183, 7.3890561 ])
Arithmetic operators on arrays (+, -, *, /, **) are also ufuncs underneath.
Boolean Indexing
Comparison operators applied to an array produce an array of boolean values:
station = np.array(['Keswick', 'Oxford', 'Oxford', 'Truro', 'Keswick'])
reading = np.array([18.3, 22.1, 21.5, 19.8, 17.9])
station == 'Keswick'
# array([ True, False, False, False, True])
One boolean array can be used to select elements from another array of the same size:
reading[station == 'Keswick']
# array([18.3, 17.9])
- Combine conditions with
&(and),|(or), and~(not) rather than the Python keywords
reading[(station == 'Keswick') | (station == 'Truro')]
# array([18.3, 19.8, 17.9])
reading[~(station == 'Oxford')]
# array([18.3, 19.8, 17.9])
Assignment
Boolean indexing also works on the left side of an assignment:
reading[station == 'Oxford'] = 0.0
print(reading)
# array([18.3, 0. , 0. , 19.8, 17.9])
Conditional Selection
You can create a new array by choosing between two values based on a condition using np.where.
- Useful as a replacement for a
forloop andifcondition over the array np.wherecomputes bothvalue_if_trueandvalue_if_falsefor the whole array first then chooses
The signature is np.where(condition, value_if_true, value_if_false)
scores = np.array([45, 72, 38, 65, 58])
# Set failing scores to 0, keep passing scores as-is
adjusted = np.where(scores >= 40, scores, 0)
# array([45, 72, 0, 65, 58])
The values for each case can be arrays:
temps = np.array([12.0, 18.0, 14.0])
fallback = np.array([15.0, 15.0, 15.0])
np.where(temps < 15, fallback, temps)
# array([15., 18., 15.])
Multiple conditions can be nested:
# Three categories: low < 50, medium 50-70, high > 70
category = np.where(scores < 50, 'low',
np.where(scores <= 70, 'medium', 'high'))
# array(['low', 'high', 'low', 'medium', 'medium'], dtype='<U6')
When there are multiple conditions, it migh be clearer to use np.select instead
conditions = [scores < 50, scores <= 70]
choices = ['low', 'medium']
np.select(conditions, choices, default='high')
# array(['low', 'high', 'low', 'medium', 'medium'], dtype='<U6')
For simple min/max clamping, use the specialised functions, which are clearer and do not need an explicit condition:
- np.maximum:
np.maximum(0, values)ensures non-negative values - np.clip:
np.clip(values, min, max)clamps within a given range
Reductions
- A reduction takes multiple elements and combines them into one such as sum, min, max, mean, std
- For multi-dimensional arrays, the
axisparameter on a ufunc controls which dimension gets reduced
grid = np.array([[18.3, 19.1, 17.6],
[20.4, 18.9, 21.0]])
grid.sum(axis=0) # array([38.7, 38., 38.6]) sum down each column
grid.sum(axis=1) # array([55.0, 60.3]) sum across each row
There are built-in reductions for common statistical and mathematical operations, see the routines by topic for a full list.
a = np.array([18.3, 19.1, 17.6, 20.4, 18.9, 21.0])
a.min() # 17.6
a.max() # 21.0
a.sum() # 115.3
a.mean() # 19.2166...
a.std() # 1.1653...
Performance Comparison
Run this to measure the difference on your own machine:
Summary
- NumPy arrays store values contiguously in memory with a uniform type
- Vectorised operations express computation on whole arrays at once, without loops
- Broadcasting lets NumPy automatically expand smaller arrays to match larger ones in operations where the shapes are compatible
- Slicing returns a view, not a copy. Mutations to a slice affect the original. Use
.copy()when you need independence
Exercises
Setup
Before starting, install these packages which we will use over the next few lectures:
uv pip install numpy pandas matplotlib scipy ipykernel
In VS Code, install the Jupyter extension, then select your Python kernel when you open a notebook. Create an iPython notebook file ending in .ipynb rather than .py.
Replacing a Loop
Here's a function that categorises temperatures using a loop:
def categorize_loop(temps):
result = []
for t in temps:
if t < 15:
result.append(0) # cold
else:
result.append(1) # warm
return result
- Rewrite this using boolean indexing. Create an array of zeros with
np.zeros(), then use boolean assignment to set warm temperatures to 1. - Now use
np.where(condition, value_if_true, value_if_false)to do it in one line. - Test both versions on
np.array([12, 18, 14, 20, 16])and verify they match the loop output.
Capping Values
Loop version:
def clamp_values(data, min_val, max_val):
result = []
for x in data:
if x < min_val:
result.append(min_val)
elif x > max_val:
result.append(max_val)
else:
result.append(x)
return result
- Rewrite using
np.clip(). - Test on
np.array([5, 15, 25, 35, 45])withmin_val=10,max_val=40.
Accumulation
Loop version:
def count_streak_breaks(values, threshold):
breaks = []
for val in values:
if val < threshold:
breaks.append(1) # streak broken
else:
breaks.append(0) # streak continues
return sum(breaks)
- Eliminate the loop using an array.
- Test on daily steps:
np.array([8000, 12000, 9500, 7000, 11000])withthreshold=10000.