Arithmetic on the whole column at once
Adding five grace marks to every student took a loop in problem 15, or a comprehension in problem 17. Both walk the list one item at a time. For five students that is instant; for five million it is slow enough to notice, and it is a great deal of typing for something so simple to say.
NumPy lets you say it simply: marks + 5.
import numpy as npas np gives it a short nickname for the rest of the file. Everything from the library is then reached through it: np.array(...). Nearly every Python programmer writes exactly this line, so np. in somebody else's code always means NumPy.np.array(marks_list) takes an ordinary list and hands back an array. It holds the same numbers, and it behaves differently in two ways worth learning now.It prints without commas — [78 65 80 92 54] rather than [78, 65, 80, 92, 54]. That is the quickest way to tell at a glance which one you are looking at.
And arithmetic applies to every value at once.
The difference that catches everyone
| You write | With a list | With an array |
|---|---|---|
| marks * 2 | [78, 65, ..., 78, 65, ...] | [156 130 160 184 108] |
| the list repeated twice | every mark doubled | |
| marks + 5 | refused outright | [83 70 85 97 59] |
A list treats * as "give me more of this" and refuses + with a number altogether. An array treats both as arithmetic on every value. Same symbols, entirely different meaning, and only the missing commas on screen to tell you which you have.
marks.shape says how the array is laid out. For a single row of five it is (5,) — a pair with one number in it and a trailing comma, which is Python's way of writing a one-item tuple.marks.dtype says what kind of numbers are inside: int64 for whole numbers, float64 once a decimal point appears. Unlike a list, an array holds one kind of thing throughout, which is exactly why it can be fast.Both are written without brackets after them. They are facts about the array, not jobs it performs.
marks + 5 builds a new array and leaves marks exactly as it was — the same courtesy sorted() showed in problem 7. If you want the raised marks kept, put them in a box.What you are building
Build the programme
Your plan
The steps still to place
The whole programme is laid out below. Five pieces are missing. Two of them turn on the difference between a fact about the array and a job it can do for you.
Leave nothing on "choose…". A wrong pick does not always cause an error — sometimes it just prints something you did not expect, which is the harder kind of mistake to spot.
Run and read
Here is the whole programme. The marks and the grace award are yours to change. Watch the two "times two" lines — they are the same instruction written twice, on two kinds of container.