Skip to course content
Free course

Python Foundations / Module 8 / Vectorised Operations

Module 8 lesson

Vectorised Operations

Unit ID: M08-U04 Estimated active time: 20-30 minutes

Vectorised code applies one operation across an array. It is usually clearer for direct numerical rules.

hours = study_minutes / 60
adjusted = study_minutes + 5

This does not mean every loop is wrong. A loop may be clearer for irregular validation or detailed rejection reasons. Use vectorisation when the same numeric operation applies to every value.

Compare:

manual = []
for value in study_minutes.ravel():
    manual.append(value / 60)

vectorised = (study_minutes / 60).ravel()
assert np.allclose(manual, vectorised)

np.allclose is useful for floating-point comparisons because many decimal values cannot be represented exactly.

Practice: convert all minutes to hours and cap every value at 90 with np.clip. State why the original source array should remain unchanged.