Local lab15 min+60 XP

Array maths

Double every price in one line. No loops required.

0% done

Run this room's code on your own computer in VS Code. You set this up in Module 07.

TASK 1

Learn it

Key idea

Array maths applies to every element at once, with no loop.

Key words
prices2.03.51.254.0* 22222the 2 is stretchedto fit: broadcasting=4.07.02.58.0
The single 2 is stretched to match every price, then multiplied.

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.

Real life linkA photo filter that brightens a picture adds a number to millions of pixels at once. NumPy does that in one line, with no loop.
Example code
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)
Output on your computer
[4.  7.  2.5 8. ]
[2.5  4.   1.75 4.5 ]
[11 22 33]
[10 40 90]
[100 400 900]
TASK 2

Try it yourself

+10 XP

Convert 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.

TASK 3

Capture the flag

+10 XP

What 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.

HOMEWORK

Order calculator

+20 XP

A 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.