Array maths
Double every price in one line. No loops required.
Run this room's code on your own computer in VS Code. You set this up in Module 07.
Learn it
Array maths applies to every element at once, with no loop.
With a list, doubling every number needs a loop. With an array, you just write prices * 2. NumPy applies the maths to every element. This is called vectorised or element-wise maths, and it is much faster than a Python loop.
When you combine an array with a single number, NumPy stretches the number to match every item. This is called broadcasting. Two arrays of the same length combine item by item: a + b adds the first items together, then the second items, and so on.
Notice that floats print without trailing zeros, like 4. for 4.0, and numbers are lined up in columns.
import numpy as np prices = np.array([2.0, 3.5, 1.25, 4.0]) print(prices * 2) print(prices + 0.5) a = np.array([1, 2, 3]) b = np.array([10, 20, 30]) print(a + b) print(a * b) print(b ** 2)
[4. 7. 2.5 8. ] [2.5 4. 1.75 4.5 ] [11 22 33] [10 40 90] [100 400 900]
Try it yourself
+10 XPConvert a whole array of Celsius temperatures to Fahrenheit in one line, with no loop.
Create a free account to start this lab
Sign in to write, run and check your code here. Your progress, XP and code are saved to your account. No card needed.
Capture the flag
+10 XPWhat does NumPy call it when a single number is stretched to combine with every item in an array?
Create a free account to start this lab
Sign in to answer the flag question. Your progress, XP and code are saved to your account. No card needed.
Order calculator
+20 XPA shop order has quantities and prices in two arrays. Multiply them to get each line total, then print the order total and the total with 20% off (rounded to 2 places). No loops allowed.
Create a free account to start this lab
Sign in to do this homework and have it checked. Your progress, XP and code are saved to your account. No card needed.