Data Analysis · NumPy Foundations · lesson 1 of 12
Arrays versus lists
about 14 minutes · free · runs in your browser
Step 1 of 2
Why another kind of list?
A Python list can hold anything, which is exactly why it is slow for numbers: every element is a separate object, and every arithmetic operation is a separate interpreted step.
A NumPy array holds one type in one contiguous block of memory, and its operations run as compiled loops:
import numpy as np
a = np.array([1, 2, 3, 4])
a.dtype # dtype('int64') — one type for the whole array
a.shape # (4,) — its dimensions
a.size # 4
The first thing that surprises people coming from lists:
[1, 2, 3] * 2 # [1, 2, 3, 1, 2, 3] — repeats the list
np.array([1, 2, 3]) * 2 # array([2, 4, 6]) — multiplies every element
That difference is the whole point. On an array, an operation means "do this to every element", and you almost never write a loop.
Your turn: build an array from readings, and record its dtype name, its
shape, and the result of doubling every value.
You start from this, and edit it in the browser:
import numpy as np
readings = [12, 15, 9, 22, 18]
# Set arr, dtype_name, shape, doubled.
Step 2 of 2
Creating arrays without a list
NumPy has its own constructors, and they are the usual way to start:
np.zeros(3) # array([0., 0., 0.])
np.ones(3) # array([1., 1., 1.])
np.arange(0, 10, 2) # array([0, 2, 4, 6, 8]) — like range()
np.linspace(0, 1, 5) # array([0., 0.25, 0.5, 0.75, 1.]) — n evenly spaced points
arange takes a step and stops before the end, exactly like range. linspace
takes a count and includes both ends — that difference catches people out.
Your turn: build evens (0 to 8 in twos), ramp (five evenly spaced points from
0 to 100 inclusive), and grid (a 2 by 3 array of zeros).
You start from this, and edit it in the browser:
import numpy as np
# Set evens, ramp and grid.