1 Before you start
This is not graded, and it does not count towards anything. Answer every question even if you are only guessing — having a go at something before you have been taught it is one of the best ways to remember it afterwards. The lesson ends with another short check, and there you will be shown the correct answer for anything you missed. Choose an option for every question and confidence rating, then click Submit answers.
What happens when you write arr.shape() with parentheses, on a NumPy array?
What is the dtype of np.array([54, 61, 72.5])?
What does np.arange(0, 10, 2) produce?
You have arr = np.array([1, 2, 3, 4]). What does arr * 2 produce?
What does np.sqrt(np.array([1, 4, 9, 16])) return?
For ages = np.array([54, 61, 47, 72, 38]), what does ages[1:4] return?
You have a 2D array m with shape (3, 4). What does m[:, 0] return?
For ages = np.array([54, 61, 47, 72, 38]), what shape does ages.reshape(-1, 1) give?
I can build a NumPy array from a Python list and read its shape, dtype, and size attributes.
I can do element-wise arithmetic on a NumPy array, index single values and slices of a 1D or 2D array, and reshape an array into a different shape.
2 Introduction
A Python list is slow for heavy number work. To change every value in a list of 1,000 patient ages, you write a loop. NumPy is a package that does this work in one line. A NumPy array looks like a list, but is stored as one tightly packed block built for fast calculation.
This lesson covers how to make an array, how to calculate on every value at once, and how to pick values out of an array.

Try every example in the Python Scratchpad on the right.
3 Introduction to NumPy arrays
NumPy is a third-party package. You load it at the top of your script with import numpy as np. This gives NumPy the short name np. So every NumPy tool is written as np.something. The function np.array turns a Python list into a NumPy array:
import numpy as np
temps = np.array([36.6, 37.2, 38.4, 36.9, 37.8, 36.4])
print(temps) # [36.6 37.2 38.4 36.9 37.8 36.4]When you print an array, the values have spaces between them and no commas. This is how you can tell an array from a list on the screen.
Try this snippet in the Python Scratchpad on the right.
import numpy as np
ages = np.array([54, 61, 47, 72, 38])
print(ages)
Every array stores information about itself, such as its shape, its type and its size. Each piece of this information is an attribute. You read an attribute with the name of the array, a dot and the name of the attribute:
import numpy as np
temps = np.array([36.6, 37.2, 38.4, 36.9, 37.8, 36.4])
print(temps.shape) # (6,)
print(temps.dtype) # float64
print(temps.size) # 6shapegives the number of values along each dimension, as a tuple. This 1D array has six values. So its shape is(6,). The comma is how Python writes a tuple with one item.dtypeis the type of the values. All the values in an array have the same type. Sodtypeis one value and not a list.sizeis the total number of values. For a 1D array, this is the same aslen(arr).
Try this snippet in the Python Scratchpad on the right.
import numpy as np
weights = np.array([72.5, 68.0, 80.2, 65.4])
print(weights.shape)
print(weights.dtype)
print(weights.size)

These three are attributes (stored data) and not methods (functions). So you write no round brackets after them.
If you add round brackets to an attribute, Python raises a TypeError. This is because Python reads the attribute as a value, and then tries to call that value like a function. In the example below, size is the whole number 6:
import numpy as np
temps = np.array([36.6, 37.2, 38.4, 36.9, 37.8, 36.4])
print(temps.size())
# TypeError: 'int' object is not callableRead the code carefully and type what you think it will print. Click Submit prediction for AI tutor feedback comparing your prediction against the real output, then click Reveal actual output to run the snippet yourself and see what happens.
import numpy as np
ages = np.array([54, 61, 47, 72, 38])
print(ages.size)
NumPy picks the type for you. Decimals become float64. Whole numbers become int64 or int32, depending on your computer and your NumPy version. The Python Scratchpad on this page shows int32. A list can mix whole numbers and decimals, but an array cannot. When a list mixes them, NumPy turns all the values into decimals:
import numpy as np
volumes_ml = np.array([2, 4, 0.5])
print(volumes_ml) # [2. 4. 0.5]The dots after the 2 and the 4 show that they are now decimals. You can choose the type yourself with the dtype keyword. These are some of the types:
- Integers (
int8toint64) store whole numbers in 8 to 64 bits. Anint8holds only the values from -128 to 127. - Unsigned integers (
uint8and so on) have no negative values. Auint8holds the values from 0 to 255. - Floats (
float32andfloat64) store decimals. Afloat64keeps 15 to 17 significant digits. Afloat32keeps about 7 digits. So it rounds off sooner.
import numpy as np
counts = np.array([3, 5, 8], dtype=np.int16)
print(counts.dtype) # int16The exercise below prints the attribute itemsize, which is the number of bytes that one value takes. It also prints 1/3 as a float64 and as a float32.
Try this snippet in the Python Scratchpad on the right.
import numpy as np
small = np.array([10, 20, 30], dtype=np.int8)
big = np.array([10, 20, 30], dtype=np.int64)
print(small.dtype, small.itemsize)
print(big.dtype, big.itemsize)
precise = np.array([1 / 3], dtype=np.float64)
rounded = np.array([1 / 3], dtype=np.float32)
print(precise)
print(rounded)
itemsizeis 1 for anint8(1 byte is 8 bits) and 8 for anint64. The two printed values of 1/3 differ in the eighth decimal place. This is because afloat32keeps only about 7 digits..astype()changes the type of an array that already exists. It gives back a new array and leaves the original array unchanged.- If you divide an integer array in place, for example with
arr /= 2, NumPy raises a casting error. This is because an integer array cannot hold decimals. So change its type tofloat64first.
import numpy as np
pulses = np.array([72, 88, 65], dtype=np.int16)
as_float = pulses.astype(np.float64)
print(as_float) # [72. 88. 65.]
print(pulses) # [72 88 65]The second print line above shows that pulses is unchanged.
Try this snippet in the Python Scratchpad on the right.
import numpy as np
scores = np.array([1, 2, 3], dtype=np.int32)
converted = scores.astype(np.float64)
print(scores, scores.dtype, scores.itemsize)
print(converted, converted.dtype, converted.itemsize)
A smaller type saves memory. But when you convert to a smaller type with .astype(), there are two risks. NumPy gives no warning when a value is too big for the new type. It wraps the value around. And NumPy cuts off decimals when it converts them to whole numbers. It does not round them. To round first, call np.round() before you convert.
import numpy as np
heart_rates = np.array([60, 128, 150])
print(heart_rates.astype(np.int8)) # [ 60 -128 -106]
temps = np.array([36.6, 37.2, 38.4, 36.9, 37.8, 36.4])
print(temps.astype(np.int32)) # [36 37 38 36 37 36]
print(np.round(temps).astype(np.int32)) # [37 37 38 37 38 36]In the example above, 128 is too big for an int8. So it wraps around to -128. And 36.9 becomes 36, not 37.
Try this snippet in the Python Scratchpad on the right.
import numpy as np
counts = np.array([120, 125, 130, 200])
prices = np.array([19.99, 4.5, 100.1])
print(counts.astype(np.int8))
print(prices.astype(np.int32))
So change to a smaller type only when you are sure of the range of your values.
NumPy also has functions that make an array for you:
np.zeros(n)makes an array ofnzeros.np.ones(n)makes an array ofnones.np.arange(start, stop, step)counts in steps fromstart. It is like the built-inrange, but it returns an array. The stop value is left out.np.linspace(start, stop, n)makesnevenly spaced values fromstarttostop. Both ends are included.
import numpy as np
print(np.zeros(3)) # [0. 0. 0.]
print(np.ones(2)) # [1. 1.]
print(np.arange(0, 60, 15)) # [ 0 15 30 45]
print(np.linspace(0, 60, 5)) # [ 0. 15. 30. 45. 60.]In the example above, np.arange stops before 60, but np.linspace includes 60.


Try this snippet in the Python Scratchpad on the right.
import numpy as np
print(np.zeros(4))
print(np.ones(3))
print(np.arange(0, 10, 2))
print(np.linspace(0, 1, 5))
4 Random number generation with np.random
Many analyses need random numbers, for example to make a fake dataset, shuffle rows or sample patients. NumPy has a module for this called np.random.
The recommended way is to make a random number generator with np.random.default_rng(seed). The seed is a number you choose. The same seed gives the same random numbers every time the code runs. So other people can repeat your analysis exactly. The code below uses the method integers to draw five whole numbers from 110 up to, but not including, 150. It does this twice with the same seed:
import numpy as np
rng = np.random.default_rng(seed=2026)
print(rng.integers(110, 150, size=5)) # [144 117 111 135 124]
rng = np.random.default_rng(seed=2026)
print(rng.integers(110, 150, size=5)) # [144 117 111 135 124]The method permutation gives back the same values in a random order.
Try this snippet in the Python Scratchpad on the right.
import numpy as np
rng = np.random.default_rng(seed=42)
ages = rng.integers(20, 90, size=10)
print(ages)
shuffled = rng.permutation(ages)
print(shuffled)

You may also see an older style: np.random.seed(0), followed by np.random.random(2). It also repeats its numbers when the seed is the same. But it uses a different generator. So its numbers are not the numbers that default_rng(0) gives:
import numpy as np
np.random.seed(0)
print(np.random.random(2)) # [0.5488135 0.71518937]
rng = np.random.default_rng(0)
print(rng.random(2)) # [0.63696169 0.26978671]5 2D or 3D NumPy arrays
Arrays are not limited to one dimension. A 2D array is a grid of values with rows and columns. This is how your data looks when you have several measurements for each patient. You make a 2D array from a list of lists. Each inner list becomes one row:
import numpy as np
vitals = np.array([
[128, 82, 71],
[141, 90, 84],
])
print(vitals)
# [[128 82 71]
# [141 90 84]]
print(vitals.shape) # (2, 3)Here each row is one patient. The three columns are the systolic pressure (mmHg), the diastolic pressure (mmHg) and the pulse (beats per minute). The shape of the array is (2, 3): the number of rows comes first, and then the number of columns.
A 3D array stacks several 2D grids. Its shape has three numbers: the number of grids, rows and columns. In the example below, each grid holds the same two patients at one visit:
import numpy as np
visit_1 = np.array([[128, 82, 71], [141, 90, 84]])
visit_2 = np.array([[124, 80, 69], [138, 88, 80]])
both = np.array([visit_1, visit_2])
print(both.shape) # (2, 2, 3)
Try this snippet in the Python Scratchpad on the right.
import numpy as np
patients = np.array([
[54, 72.5, 1.75],
[61, 68.0, 1.80],
[47, 80.2, 1.68]
])
print(patients)
print(patients.shape)

The shape of this array is (3, 3): three rows and three columns.
A NumPy array and a Python list look alike, but they follow different rules:
- Types: a list can mix any kinds of values. All the values in an array have the same type.
- Size: a list can grow when you append a value. An array has a fixed length. So to add a value, you make a new array.
- Calculations: an array does arithmetic on every value at once, as the next sections show. A list cannot do this.

6 Array broadcasting and operations
Suppose you have blood glucose readings in mg/dL. You need each reading in mmol/L. For this, you divide every reading by 18. With a Python list, you write a loop. The loop visits each value, divides it and adds the result to a new list:
glucose_mgdl = [90, 126, 108, 162]
glucose_mmol = []
for value in glucose_mgdl:
glucose_mmol.append(value / 18)
print(glucose_mmol) # [5.0, 7.0, 6.0, 9.0]With a NumPy array, you write one expression and no loop:
import numpy as np
glucose_mgdl = np.array([90, 126, 108, 162])
print(glucose_mgdl / 18) # [5. 7. 6. 9.]NumPy divides every value by 18. This is called broadcasting. NumPy stretches the single number across every position of the array.

6.1 Element-wise arithmetic
The first benefit of NumPy is element-wise arithmetic. Adding a number to an array applies the addition to every element without a loop. The same is true for subtraction, multiplication, division and exponentiation. This example converts temperatures from degrees Celsius to degrees Fahrenheit:
import numpy as np
temps_c = np.array([36.5, 37.0, 38.5])
temps_f = temps_c * 1.8 + 32
print(temps_f) # [ 97.7 98.6 101.3]
print(temps_c) # [36.5 37. 38.5]The second print line shows the original array remains unchanged.

Try this snippet in the Python Scratchpad on the right.
import numpy as np
ages = np.array([54, 61, 47, 72, 38])
print(ages + 5)
print(ages * 2)
Each calculation returns a new array. Give the result a name to keep it.
NumPy runs these calculations in fast, compiled code. With a million values, this is much faster than a loop.
Two more operators work on every element: // (floor division) and % (modulo, the remainder after division). You already used both on single numbers. This example splits durations in minutes into whole hours and leftover minutes:
import numpy as np
minutes = np.array([75, 130, 45, 200])
print(minutes // 60) # [1 2 0 3]
print(minutes % 60) # [15 10 45 20]Try this snippet in the Python Scratchpad on the right.
import numpy as np
ages = np.array([54, 61, 47, 72, 38])
print(ages // 10)
print(ages % 10)
Every example so far combines an array with a single number. NumPy can also combine two arrays of the same length. It pairs values by position. The first value pairs with the first, the second with the second, and so on. This example multiplies each daily dose by its number of days:
import numpy as np
daily_dose_mg = np.array([250, 500, 750])
days = np.array([5, 7, 10])
print(daily_dose_mg * days) # [1250 3500 7500]
days = np.array([5, 7])
print(daily_dose_mg * days)
# ValueError: operands could not be broadcast together with shapes (3,) (2,)NumPy raises a ValueError if the arrays have different lengths. It does not guess which values belong together.
Try this snippet in the Python Scratchpad on the right.
import numpy as np
before = np.array([148, 152, 139, 161, 144])
after = np.array([136, 140, 130, 142, 133])
change = after - before
print(change)
Each value in change is after - before at the same position. These are five separate subtractions written as one expression without a loop or indexing.
You can combine several operators and arrays in one expression. The next example calculates the body-mass index of three patients.
Try this snippet in the Python Scratchpad on the right.
import numpy as np
weights = np.array([72.5, 68.0, 80.2])
heights = np.array([1.75, 1.80, 1.68])
bmi = weights / (heights ** 2)
print(bmi)

6.2 Broadcasting beyond arithmetic
You have seen that a single number can be combined with a whole array. The same idea works for two arrays when their shapes are compatible. For example, you can combine a grid with a single row. The grid below holds the systolic blood pressure of five patients at three visits. The cuff read too high by a different amount at each visit. So one row holds the three corrections:
import numpy as np
systolic = np.array([
[148, 142, 138],
[135, 131, 129],
[162, 155, 149],
[127, 124, 121],
[141, 136, 133],
])
corrections = np.array([6, 4, 2])
corrected = systolic - corrections
print(corrected)
# [[142 138 136]
# [129 127 127]
# [156 151 147]
# [121 120 119]
# [135 132 131]]
print(systolic - np.array([6, 4]))
# ValueError: operands could not be broadcast together with shapes (5,3) (2,)The shapes are (5, 3) and (3,). NumPy compares them from the right. The last numbers are both 3. So the row fits, and NumPy stretches it down all five rows. A row of two values does not fit. This is because 3 and 2 are not equal. So the last line raises a ValueError.
In general, two arrays can broadcast when each pair of numbers in their shapes is either equal or one of them is 1.
The next example uses patients.mean(axis=0), which gives the mean of each column as a row of three values.
Try this snippet in the Python Scratchpad on the right.
import numpy as np
patients = np.array([
[54, 72.5, 1.75],
[61, 68.0, 1.68],
[47, 80.2, 1.82],
])
column_means = patients.mean(axis=0)
print(column_means)
centred = patients - column_means
print(centred)

NumPy also has mathematical functions that work on every value of an array. Each returns a new array of the same shape. The np.abs function removes the minus sign from every value:
import numpy as np
changes = np.array([-7, 4, -3, 9])
print(np.abs(changes)) # [7 4 3 9]The function np.sqrt gives the square root of every value.
Try this snippet in the Python Scratchpad on the right.
import numpy as np
values = np.array([1, 4, 9, 16, 25])
print(np.sqrt(values))
6.3 Math functions: np.log and np.exp
The np.log function gives the natural logarithm of every value. The np.exp function raises e to the power of every value. So np.exp reverses np.log. Lab results are often spread over a wide range. The logarithm brings large values closer to small ones. This example uses three CD4 counts, in cells per microlitre:
import numpy as np
cd4 = np.array([50, 200, 500])
logs = np.log(cd4)
print(np.round(logs, 1)) # [3.9 5.3 6.2]
print(np.exp(logs)) # [ 50. 200. 500.]Try this snippet in the Python Scratchpad on the right.
import numpy as np
values = np.array([1, 10, 100, 1000])
print(np.log(values))
print(np.exp([0, 1, 2]))

7 Array indexing
You pick one value from a 1D array with square brackets, as you do for a list. The first value has index 0, and the last value has index -1. A slice arr[a:b] gives a smaller array. It starts at index a and stops before index b:
import numpy as np
temps = np.array([36.6, 37.2, 38.4, 36.9, 37.8, 36.4])
print(temps[2]) # 38.4
print(temps[-1]) # 36.4
print(temps[2:4]) # [38.4 36.9]The slice temps[2:4] has two values, not three. This is because index 4 is left out.

Try this snippet in the Python Scratchpad on the right.
import numpy as np
ages = np.array([54, 61, 47, 72, 38])
print(ages[0])
print(ages[-1])
print(ages[1:4])
A slice is itself a NumPy array. A slice from a to b has b - a values.
A 2D array has two axes: the rows and the columns. You write two numbers, the row and then the column, in the form arr[row, column]. A colon in place of a number means all of that axis. The example below uses a table of five patients. The columns are the systolic pressure, the diastolic pressure and the pulse:
import numpy as np
vitals = np.array([
[128, 82, 71],
[141, 90, 84],
[119, 76, 66],
[135, 88, 92],
[152, 95, 78],
])
print(vitals[2, 1]) # 76
print(vitals[1, :]) # [141 90 84]
print(vitals[:, 2]) # [71 84 66 92 78]The last line gives the pulse of every patient. A column comes back as a 1D array. So NumPy prints it on one line.

Try this snippet in the Python Scratchpad on the right.
import numpy as np
patients = np.array([
[54, 72.5, 1.75],
[61, 68.0, 1.80],
[47, 80.2, 1.68]
])
print(patients[0, 1])
print(patients[0, :])
print(patients[:, 0])
In the example above, patients[0, 1] is the weight of the first patient, 72.5. The form patients[0, :] is the whole first row.
In plain Python, you pick a value from a list of lists with grid[1][2]. A NumPy array also accepts this form, but the usual form is grid[1, 2]. It picks the value in one step. It also lets you pick a whole column, as in grid[:, 2].

To pick one value from a 3D array, you write three numbers: the grid, the row and the column. The example below uses the two visits from earlier in this lesson:
import numpy as np
visit_1 = np.array([[128, 82, 71], [141, 90, 84]])
visit_2 = np.array([[124, 80, 69], [138, 88, 80]])
both = np.array([visit_1, visit_2])
print(both[1, 0, 2]) # 69The three numbers pick grid 1 (the second visit), row 0 (the first patient) and column 2 (the pulse).
The method reshape gives back the same values in a new layout. This is useful when the values of a long 1D array belong in a grid. For example, six readings may be two patients with three measurements each:
import numpy as np
values = np.array([4.1, 3.8, 5.0, 4.4, 3.9, 4.7])
grid = values.reshape(2, 3)
print(grid.shape) # (2, 3)
Read the code carefully and type what you think it will print. Click Submit prediction for AI tutor feedback comparing your prediction against the real output, then click Reveal actual output to run the snippet yourself and see what happens.
import numpy as np
x = np.arange(12)
y = x.reshape(3, 4)
print(y.shape)
The new layout must hold exactly as many values as the array has. Two rows of three hold six values. So reshaping the six readings works. Four rows of two hold eight values. So NumPy raises a ValueError:
import numpy as np
values = np.array([4.1, 3.8, 5.0, 4.4, 3.9, 4.7])
print(values.reshape(4, 2))
# ValueError: cannot reshape array of size 6 into shape (4,2)The method reshape groups a flat array into more dimensions. The method .flatten() does the reverse. It turns an array of any shape into a 1D array, reading it out row by row.
Try this snippet in the Python Scratchpad on the right.
import numpy as np
grid = np.array([[1, 2, 3], [4, 5, 6]])
print(grid.flatten())
The method .ravel() gives the same result and is often faster. This is because it returns a view whenever it can. A view shares its stored values with the original array. So a change to the view also changes the original. The method .flatten() always returns a copy. A copy has its own values. So a change to the copy never changes the original. The example below shows the difference:
import numpy as np
grid = np.array([[10, 20, 30], [40, 50, 60]])
flat_view = grid.ravel()
flat_copy = grid.flatten()
flat_view[0] = 99
flat_copy[1] = 77
print(grid[0, 0]) # 99
print(grid[0, 1]) # 207.1 The reshape(-1, 1) idiom
A 1D array of n values has the shape (n,). Many tools need a 2D column of shape (n, 1) instead. This is one column with n rows. You make it with .reshape(-1, 1). The -1 tells NumPy to work out that number from the total number of values. So you do not have to count. The example below uses six values:
import numpy as np
values = np.array([4.1, 3.8, 5.0, 4.4, 3.9, 4.7])
print(values.reshape(-1, 3).shape) # (2, 3)
print(values.reshape(-1, 1).shape) # (6, 1)With -1, 3, NumPy works out 2 rows. With -1, 1, it works out 6 rows.
Try this snippet in the Python Scratchpad on the right.
import numpy as np
ages = np.array([54, 61, 47, 72, 38])
print(ages.shape)
column = ages.reshape(-1, 1)
print(column)
print(column.shape)

8 Check your understanding
You have reached the end of the module. Try the same questions again — your answers here, paired with your pre-test answers, are how we measure what the module taught you. Answer every question and confidence rating, then click Submit and see results to view your score.
What happens when you write arr.shape() with parentheses, on a NumPy array?
What is the dtype of np.array([54, 61, 72.5])?
What does np.arange(0, 10, 2) produce?
You have arr = np.array([1, 2, 3, 4]). What does arr * 2 produce?
What does np.sqrt(np.array([1, 4, 9, 16])) return?
For ages = np.array([54, 61, 47, 72, 38]), what does ages[1:4] return?
You have a 2D array m with shape (3, 4). What does m[:, 0] return?
For ages = np.array([54, 61, 47, 72, 38]), what shape does ages.reshape(-1, 1) give?
I can build a NumPy array from a Python list and read its shape, dtype, and size attributes.
I can do element-wise arithmetic on a NumPy array, index single values and slices of a 1D or 2D array, and reshape an array into a different shape.
9 Your results
Here is how your post-test answers compare with your pre-test answers. The pre/post pairing is the most reliable way to see what this module actually taught you.
Submit the post-test to see your results.
What is the one thing from this module that is still unclear to you?