NumPy arrays: why not lists
Why it matters A network does millions of multiplications. NumPy does them in fast compiled code, so one line replaces a whole loop and runs far faster.
A NumPy array is a block of numbers that all have the same type. Arithmetic on an array happens to every item at once:
import numpy as np
a = np.array([1, 2, 3])
a * 10 # array([10, 20, 30])
(a ** 2).sum() # 14
See it
With a list you write the loop; with an array NumPy runs the loop for you in C. On a million numbers the array version is usually 20 to 100 times faster. You can time it yourself with time.perf_counter() before and after.
Vectorised: written as whole-array operations instead of a Python loop.
Recap Lists are flexible; arrays are fast and do maths on every item at once.
Words and symbols in this lesson
- array
- a NumPy block of numbers, all the same type, that does maths on every item at once
Write sum_of_squares(a) that takes a NumPy array and returns the sum of its squares, with no Python loop (no for, no while, no comprehension).
Spotted a problem in this lesson? Report it · Ask about this lesson
This exercise opens soon
Finish the lesson before it and this one unlocks. The whole course is free, no account needed, and you can read this lesson right now.
This browser is blocking cookies for learn.floati.life, so lessons you finished here cannot open in order. Allow cookies for this site and reload.