Menu
CoddyTech

Math on Whole Arrays

Part of the Data and Plots section of Coddy's Machine Learning journey. Lesson 10 of 60.

A shop sold 3, 1 and 2 of its three items. A list would need a loop to find what each earned. An array pairs the values up:

Three rows of cells: prices 4, 10, 25 above sold 3, 1, 2, and below them earned 12, 10, 50, each the product of the two cells above it

In code:

prices = np.array([4, 10, 25])
sold = np.array([3, 1, 2])
print(prices * sold)
print(prices * 2)

This prints:

[12 10 50]
[ 8 20 50]

A single number reaches every value: prices * 2 doubles them all. This is element-wise math: no loop, no index.

The same goes for +, -, / and **. Division always gives decimals.

By this chapter's end, lines like these will grade a whole class.

challenge icon

Challenge

Easy

A runner logged three runs. The program reads their distances into km and their times into minutes. Without a loop:

  1. Make meters: every distance in meters (1 km is 1000 m).
  2. Make pace: each run's minutes per kilometer, its time divided by its distance.
  3. Print both after their labels, as below.

For runs of 5, 10 and 4 km that took 30, 55 and 26 minutes:

Meters: [ 5000 10000  4000]
Minutes per km: [6.  5.5 6.5]

Try it yourself

import numpy as np

km = np.array([int(input()), int(input()), int(input())])
minutes = np.array([int(input()), int(input()), int(input())])

# Write your code below
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Data and Plots

Practice on your own: Online Python compiler