NumPy Tutorial for Beginners: Arrays, Calculations and Data Science Examples
The school weather club’s noon thermometer touched 30 °C once in the second week. Was that single reading enough to make the week warmer on average? Fourteen numbers fit on a scrap of paper. To answer the question, you need their order, a fair comparison and a way to check your arithmetic.

In this NumPy tutorial for beginners, you will create arrays, select days, compare averages and plot two fictional weeks. Before running each example, predict one output. Change one input and explain the difference.
The project uses invented readings. Day numbers identify observations. Temperatures measure degrees Celsius. Both can be integers while answering different questions.
Jump to a lesson
What is NumPy in Python?
NumPy is an open-source Python library for numerical computing. Its ndarray holds values along one or more axes. Imagine five exam scores in a line. An array preserves their order and lets you select the first score, add points to every score or find a mean.
A dimension is a direction along which you can choose a position. A row of scores needs one position. A timetable needs two, such as a weekday and a lesson period. The numbers alone do not tell the computer which axis means which. Write that meaning beside your data. If lists and variables are new to you, start with the first examples in Python for Data Science Beginners.
Why use NumPy for data science?
A school laboratory might take one light reading at each of six locations, then repeat the experiment. With an array, the same unit conversion can apply to every reading, and the same averaging rule can apply to each location. This is vectorization. You describe an operation on a collection and NumPy handles the element-by-element work. Many numerical operations use compiled routines internally.
Array elements share one data type, which can make storage and arithmetic efficient. Python lists suit mixed objects. Pandas adds named columns, Matplotlib draws values, and SciPy and many machine-learning tools accept arrays as inputs. See how these tools fit an investigation in our introduction to data science.
Set up a notebook and import NumPy
Use Google Colab
Open Google Colab, create a notebook and enter the Python import and print statements below in a code cell. Press Shift+Enter to see the installed version. Rerun setup cells after restarting the runtime, because a restart clears its variables.
Use Python on your computer
Run these terminal commands with your usual Python interpreter, substituting python3 if needed. Matplotlib draws the project chart. On school computers, follow the approved setup. Find other practice options in the school Python learning guide.
python -m pip install numpy
python -m pip install matplotlib
import numpy as np
print(np.__version__)
The alias np is conventional. Your version number depends on the installation. Each Python example runs in its own cell. Copy the code and compare your result with the output underneath.
Create your first NumPy array
Put the numbers inside square brackets and pass that sequence to np.array(). An integer can represent a whole-number exam score. A floating-point value can represent a decimal reading, such as 24.5 °C. The array’s dtype tells you how NumPy stores its elements. Choose a type that preserves the precision your question needs.
import numpy as np
scores = np.array([65, 72, 80, 88, 94])
print(scores)
readings = np.array([24.0, 24.5], dtype=np.float64)
print(readings.tolist(), readings.dtype)
Output [65 72 80 88 94] [24.0, 24.5] float64
NumPy prints the scores with spaces, although the input list uses commas. The readings explicitly use float64. Try replacing 24.5 with 24.75. Assigning that reading to an integer array would discard the fractional part.
Python lists and NumPy arrays behave differently
Imagine three rounds worth 1, 2 and 3 points. Doubling each award should give six points in the last round. Predict what the multiplication below does to each container.
import numpy as np
values = [1, 2, 3]
print(values * 2)
print(np.array(values) * 2)
Output [1, 2, 3, 1, 2, 3] [2 4 6]
| Question | Python list | NumPy array |
|---|---|---|
| What can it hold? | Mixed Python objects | One dtype for all elements |
| What does * 2 do? | Repeats the sequence | Doubles each numeric value |
| Good first use | A list of equipment | A set of measured lengths |
Apply this to a budget. Doubling a list of prices makes the shopping list twice as long. Multiplying a numerical price array by two changes what each item costs.
![Multiplying the list [1, 2, 3] by two repeats it. Multiplying a NumPy array with the same values gives [2, 4, 6].](https://notesforshs.com/wp-content/uploads/2026/11/numpy-python-list-multiplication.webp)
Read dimensions, shape and size
A club records three trials for each of two teams. Rows stand for teams and columns for trials. Read shape in axis order. Here (2, 3) means two rows of three. size counts all six entries and ndim counts the two axes.
import numpy as np
strip = np.array([2, 4, 6, 1, 3, 5])
grid = np.array([[2, 4, 6], [1, 3, 5]])
pair = np.stack([grid, grid])
for item in (strip, grid, pair):
print(item.ndim, item.shape, item.size)
Output 1 (6,) 6 2 (2, 3) 6 3 (2, 2, 3) 12

In (6,), the comma marks a one-item tuple. Stacking the two-team table twice adds an outer axis, giving (2, 2, 3). Two sessions times two teams times three trials checks the size of twelve.
Choose the right array-creation function
Use zeros to initialize counters you will update, ones for a uniform starting weight and full for a chosen starting value. Zero can be a real measurement. If a rain gauge was never read, a zero would incorrectly describe a dry day. Use a documented missing value when an observation is unknown.
import numpy as np
print(np.zeros(3, dtype=int))
print(np.ones((2, 2), dtype=int))
print(np.full(3, 25))
print(np.arange(0, 7, 2))
print(np.linspace(0, 1, 5))
Output [0 0 0] [[1 1] [1 1]] [25 25 25] [0 2 4 6] [0. 0.25 0.5 0.75 1. ]
With arange, you specify a step and the stop is excluded. Counting by twos from zero towards seven gives zero, two, four and six. With linspace, you specify the number of evenly spaced values and the endpoint is included by default. To mark five points along a one-metre ruler, including both ends, the spacing must be one quarter of a metre. Try asking for three points instead.
Select individual values by index
The first of five scores is at index 0 and the fifth at index 4. Negative indices count backwards, so −1 selects the last value. For a table, separate the row and column positions with a comma.
import numpy as np
scores = np.array([65, 72, 80, 88, 94])
grid = np.array([[2, 4, 6], [1, 3, 5]])
print(scores[0], scores[-1], grid[1, 0])
print(grid[0, 2])
Output 65 94 1 6
grid[1, 0] is the second team’s first trial. Find the first team’s third trial in the diagram. Its value is 6 because column index 2 is the third position.
Slice rows and columns and protect your original data
In array[start:stop:step], the start is included and the stop excluded. A blank boundary uses the appropriate end for that direction. Try the first two scores, the final two and every other score.
import numpy as np
scores = np.array([65, 72, 80, 88, 94])
grid = np.array([[2, 4, 6], [1, 3, 5]])
print(scores[:2], scores[-2:])
print(scores[1:4], scores[::2])
print(grid[:, 1])
print(grid[:1, 1:])
Output [65 72] [88 94] [72 80 88] [65 80 94] [4 3] [[4 6]]
In grid[:, 1], the colon selects every row and the 1 selects the second column. grid[:1, 1:] keeps a two-dimensional table with one row. Predict both shapes before inspecting them.
When a slice shares its data
Basic array slices usually return a view. The view and the original share stored values, so writing through the view can alter the original. Make a copy before experimenting if you need to keep the original measurements for your report.
import numpy as np
raw = np.array([10, 20, 30, 40])
window = raw[1:3]
saved = window.copy()
window[0] = 99
print(raw, saved)
Output [10 99 30 40] [20 30]
The raw data now contain 99. The saved copy still contains 20. Try changing the copy and checking the original again.
Calculate with whole arrays
Equal-shaped arrays pair values at corresponding positions. Addition combines each pair, subtraction gives a difference, multiplication scales or combines factors, and division gives a ratio. The power operator raises each value to an exponent. The school canteen might multiply a quantity array by a unit-price array to obtain one cost per item.
import numpy as np
first = np.array([4, 6, 8])
second = np.array([2, 3, 4])
print(first + second, first - second)
print(first * second, first / second)
print(second ** 2)
Output [ 6 9 12] [2 3 4] [ 8 18 32] [2. 2. 2.] [ 4 9 16]
Check one position by hand. In the last position, eight divided by four gives two, while four squared gives sixteen. Pairing by position assumes the items are in the same order. In a cost-per-item calculation, check the denominator for zero first. Floating-point division by zero can produce infinity or a missing numerical result and a warning.
NumPy broadcasting explained
Suppose a scoring rule awards two bonus points in every trial. The number 2 is a scalar. When it is added to a table, NumPy applies it at each position. Broadcasting makes that operation possible without requiring you to construct a second table filled with twos.
import numpy as np
grid = np.array([[2, 4, 6], [1, 3, 5]])
print(grid + 2)
offsets = np.array([10, 20, 30])
print(grid + offsets)
Output [[4 6 8] [3 5 7]] [[12 24 36] [11 23 35]]
![Adding 2 changes the rows [2, 4, 6] and [1, 3, 5] to [4, 6, 8] and [3, 5, 7].](https://notesforshs.com/wp-content/uploads/2026/11/numpy-scalar-broadcasting-bonus.webp)
The second calculation gives a different bonus to each trial. Starting at the right, the length three of offsets matches the grid’s three columns. Its absent leading axis acts like length one, so the same three bonuses apply to both rows. Matching axes must have equal lengths or one of them must be one. A length-two array cannot line up with these three columns. To give one bonus per team, use a column of shape (2, 1).
Reshape, transpose or flatten an array
Look back at the array diagram. Reading across the first row and then the second produces the original strip of six numbers. reshape(2, 3) arranges those same six values in two rows. The element count must agree on both sides. Asking for four rows of two would require eight values.
import numpy as np
strip = np.array([2, 4, 6, 1, 3, 5])
grid = strip.reshape(2, 3)
print(grid)
print(grid.transpose())
print(grid.flatten(), grid.ravel())
Output [[2 4 6] [1 3 5]] [[2 1] [4 3] [6 5]] [2 4 6 1 3 5] [2 4 6 1 3 5]
transpose() exchanges the row and column axes of this table, so the first row of the transposed result is 2 and 1. flatten() returns an independent one-dimensional copy. ravel() can share storage when the layout permits and makes a copy when necessary. Reshaping can also return a view. If independence matters, request a copy explicitly. Try predicting the shape of the transposed grid before running the example.
Describe the centre and spread of scores
Three practice marks are 60, 70 and 80. Their sum is 210, so their mean is 210 divided by three, or 70. The ordered middle mark, the median, is also 70. The minimum and maximum give the endpoints. Replacing 80 with 100 would move the mean while the median would stay at 70. This is one reason to report both.
import numpy as np
marks = np.array([60, 70, 80])
print(marks.sum(), marks.min(), marks.max())
print(np.mean(marks), np.median(marks))
print(round(np.var(marks), 2), round(np.std(marks), 2))
print(np.var(marks, ddof=1), np.std(marks, ddof=1))
Output 210 60 80 70.0 70.0 66.67 8.16 100.0 10.0
For a manual variance check, subtract the mean from each mark. The deviations are −10, 0 and 10. Their squares sum to 200. Treating these three marks as the complete group gives a variance of 200 divided by three, about 66.67 squared points. Its square root is a standard deviation of about 8.16 points. Squaring prevents opposite deviations cancelling each other.
NumPy defaults to ddof=0, which divides by the number of observations. When estimating a wider population’s variance from an appropriate sample, ddof=1 divides by one fewer. Here that gives a variance of 100 and a sample standard deviation of 10. One observation is insufficient for that sample calculation. The maths behind data science guide gives more opportunities to connect a formula to a question.
Generate repeatable random values
A simulation is a way to explore what a model might produce. Imagine five throws of a six-sided die. Create a generator using default_rng, then request integers from one up to seven. The upper boundary is excluded, giving the six possible faces. A seed lets a class replay the example in the same software environment.
import numpy as np
rng = np.random.default_rng(46)
throws = rng.integers(1, 7, size=5)
print(throws)
replay = np.random.default_rng(46).integers(1, 7, size=5)
print(np.array_equal(throws, replay))
Output [4 6 2 1 4] True
Reinitializing the generator reproduces the draws in this environment. Another draw from the first generator advances its state. Record the seed and software version. Simulated throws cannot establish how a physical die behaves.
Use a Boolean mask to select values
A comparison makes an array of true or false decisions, one for each position. Using that mask inside square brackets selects the values that passed. Predict whether exactly 70 would pass the rule below, even though 70 is absent from the input.
import numpy as np
scores = np.array([45, 62, 71, 88, 93])
keep = scores >= 70
print(keep)
print(scores[keep])
Output [False False True True True] [71 88 93]
The three true positions supply 71, 88 and 93 in order. Changing >= to > matters whenever a score equals the threshold. Write the comparison in words before typing it. You will make exactly this decision when the weather club asks for days above 27 °C.
Combine arrays and compare pairs
concatenate joins along an existing axis. vstack places these teams in rows. hstack puts copies of the resulting table side by side. Use the printed shape to check which direction grew.
import numpy as np
home = np.array([2, 4, 6])
away = np.array([1, 3, 5])
print(np.concatenate((home, away)))
rows = np.vstack((home, away))
print(rows)
print(np.hstack((rows, rows)).shape)
print(np.where(home > away, "home", "away"))
Output [2 4 6 1 3 5] [[2 4 6] [1 3 5]] (2, 6) ['home' 'home' 'home']
where chooses between two labels for each comparison. In this example the home value wins all three trials. With the rule shown, a tie would receive the label “away”. If draws are possible, decide how to label them before using this code to report a match.
Analysing Weekly Temperature Data Using NumPy
Which week had the higher average noon temperature, and which had more variation? Imagine one shaded location and fourteen consecutive noon readings. The first seven entries form week one. This complete script creates the fictional data and checks both questions.

import numpy as np
temps = np.array([
24, 25, 23, 26, 25, 27, 25,
26, 28, 25, 29, 27, 30, 24
])
days = np.arange(1, temps.size + 1)
weeks = temps.reshape(2, 7)
print("Shape:", weeks.shape)
print("Overall mean:", temps.mean())
print("Lowest and highest:", temps.min(), temps.max())
print("Days above 27:", days[temps > 27])
print("Weekly means:", weeks.mean(axis=1))
print("Weekly SDs:", np.round(weeks.std(axis=1), 2))
print("Overall SD:", round(temps.std(), 2))
Output Shape: (2, 7) Overall mean: 26.0 Lowest and highest: 23 30 Days above 27: [ 9 11 13] Weekly means: [25. 27.] Weekly SDs: [1.2 2. ] Overall SD: 1.93
The row shape ensures that axis=1 averages across seven days, giving one answer per week. Averaging on axis zero would instead pair the same weekday in the two weeks. The weekly means are 25 and 27 °C. A separate check comes from the sums of 175 and 189. Because both weeks have seven readings, their combined mean is 26 °C.
The lowest reading was 23 °C on day 3 and the highest was 30 °C on day 13. Days 9, 11 and 13 exceeded 27 °C. Week two also had the larger population standard deviation, 2.00 °C compared with about 1.20 °C. The result describes the fourteen invented noon readings. Different measurement times, missing days or an exposed sensor could change a real comparison.
Try removing day 13 on paper. The other six readings of week two sum to 159, giving a mean of 26.5 °C. The single warmest day contributed to the difference, but the second week would still have a higher mean than the first. Unequal sample sizes now matter if you combine the weeks.
Plot the temperature record with Matplotlib
A line chart keeps time in order. Put day number on the horizontal axis and degrees Celsius on the vertical axis. The dashed reference marks the threshold and diamonds identify readings that exceed it. The following cell includes all fourteen values so it can run in a fresh Python session with both libraries installed.
import numpy as np
import matplotlib.pyplot as plt
temps = np.array([
24, 25, 23, 26, 25, 27, 25,
26, 28, 25, 29, 27, 30, 24
])
days = np.arange(1, temps.size + 1)
hot = temps > 27
plt.rcParams.update({"font.size": 14})
fig, ax = plt.subplots(figsize=(7.8, 4.8), layout="constrained")
ax.plot(days, temps, "o-", color="#12684e", linewidth=2)
ax.axhline(27, linestyle="--", color="#65736d", label="27 °C")
ax.scatter(days[hot], temps[hot], color="#a24819", zorder=3,
marker="D", label="Above 27 °C")
ax.set(title="Fictional noon temperatures over 14 days",
xlabel="Day of observation", ylabel="Temperature (°C)",
xticks=[1, 3, 5, 7, 9, 11, 13], yticks=range(23, 32, 2),
ylim=(22, 32))
ax.grid(axis="y", alpha=0.2)
ax.legend(loc="upper left", ncols=2)
plt.show()

From day 13 to day 14 the temperature falls six degrees. A higher weekly average can hide a sharp daily fall. The line connects noon observations. Conditions between readings are unknown.
Diagnose common NumPy mistakes
A NameError mentioning np usually means the import cell has not run. A list that grows longer under multiplication needs conversion to an array when you want arithmetic. For an IndexError, compare the requested position with the axis length. For a broadcasting or reshape ValueError, check the shapes and the total size before changing your numbers.
If an answer has the right values arranged the wrong way, inspect ndim and shape. If a raw value changes unexpectedly, ask whether you edited a slice. If decimals disappear, inspect dtype. For an unexpected standard deviation, check the axis, the observations included and the chosen divisor.
import numpy as np
rain = np.array([2.0, np.nan, 6.0])
print(np.isnan(rain))
print(np.mean(rain), np.nanmean(rain))
print(np.count_nonzero(~np.isnan(rain)))
Output [False True False] nan 4.0 2
The missing rain reading is represented by np.nan in a floating-point array. The ordinary mean returns NaN. The missing-aware mean returns four millimetres from two observed days. Report the count alongside it. Treating the missing day as zero would answer a different question.
Ten NumPy exercises with worked answers
Predict each result before opening its answer. Change one number or boundary and check your explanation.
1. Create an array. A rain gauge records 0, 4 and 8 millimetres on three days. Make an integer array, then print its numbers and its number of dimensions.
Check answer 1
import numpy as np
rain = np.array([0, 4, 8])
print(rain, rain.ndim)
Output [0 4 8] 1
2. Read a shape. Two teams each record three attempts. Build the grid from the shape diagram and print the number of rows, columns and measurements.
Check answer 2
import numpy as np
grid = np.array([[2, 4, 6], [1, 3, 5]])
print(*grid.shape, grid.size)
Output 2 3 6
3. Select a measurement. In the same grid, predict the value in the second row and third column. Confirm your prediction using one indexing expression.
Check answer 3
import numpy as np
grid = np.array([[2, 4, 6], [1, 3, 5]])
print(grid[1, 2])
Output 5
4. Slice a sequence. Take positions one and three from the five examination scores in the first example. Use one slice and explain where it stops.
Check answer 4
import numpy as np
scores = np.array([65, 72, 80, 88, 94])
print(scores[1:4:2])
Output [72 88]
The stop at index 4 is excluded.
5. Convert units. Three seedlings grew 1.5, 2.0 and 2.5 centimetres. Convert all three measurements to millimetres in a single operation.
Check answer 5
import numpy as np
growth_cm = np.array([1.5, 2.0, 2.5])
print(growth_cm * 10)
Output [15. 20. 25.]
6. Check a mean. A player records 4, 6 and 11 successful passes in three short drills. Work out the mean by hand and use an array to check it.
Check answer 6
import numpy as np
print(np.mean([4, 6, 11]))
Output 7.0
The three counts total 21, giving seven passes per drill.
7. Filter by threshold. Pick the values strictly greater than 27 from readings of 27, 28, 25 and 30 degrees. Predict what changes if you include equality.
Check answer 7
import numpy as np
t = np.array([27, 28, 25, 30])
print(t[t > 27], t[t >= 27])
Output [28 30] [27 28 30]
8. Reshape and reduce. Put the integers 1 through 6 into a two-row table. Find the sum of each row. Decide which axis disappears from the answer.
Check answer 8
import numpy as np
table = np.arange(1, 7).reshape(2, 3)
print(table.sum(axis=1))
Output [ 6 15]
Summing across axis 1 leaves one sum per row.
9. Replay a simulation. Generate four whole numbers from 0 through 9 using seed 12. Start a second generator with the same seed and test the two arrays for equality.
Check answer 9
import numpy as np
a = np.random.default_rng(12).integers(0, 10, 4)
b = np.random.default_rng(12).integers(0, 10, 4)
print(a, np.array_equal(a, b))
Output [6 2 9 9] True
10. Interpret the weather log. Use the project array to calculate the difference between the weekly means. Write one sentence about this location and time window, and name one piece of information you would want before comparing real months.
Check answer 10
import numpy as np
temps = np.array([
24, 25, 23, 26, 25, 27, 25,
26, 28, 25, 29, 27, 30, 24
])
means = temps.reshape(2, 7).mean(axis=1)
print(means[1] - means[0])
Output 2.0
Week two averaged 2 °C warmer during the fictional fortnight. To compare real months, check observation times and missing days.
A four-week NumPy learning roadmap
Adjust the timetable to your school week. At each stage, save one working example you can explain without reading the code aloud.
| Week | Learning goal | Something to keep |
|---|---|---|
| 1 | Build arrays and explain their shapes and types. | An annotated six-value grid. Compare notebook tools. |
| 2 | Predict indices, slices and arithmetic results. | Three predictions checked against actual output. |
| 3 | Explain broadcasting, reshape and spread. | A manual calculation alongside its NumPy check. |
| 4 | Complete and interpret the temperature project. | A labelled chart and a limitation. Adapt it for a science project. |
Frequently asked questions about NumPy
What is NumPy used for in Python?
It stores numerical data in arrays and performs calculations across those values. A school project can use it to convert units, compare weeks or summarize repeated measurements.
Is NumPy difficult for beginners?
Start with five numbers and a calculation you can check by hand. Add a second dimension only when you can describe what each row and column represents.
How much Python do I need first?
Knowing variables, lists and print is enough to begin. The getting-started guide can help you plan the first sessions.
Is NumPy free to use?
Yes. NumPy is open-source software available to install and use without a licence fee. A hosted notebook or an optional course can have its own access terms.
What does ndarray mean?
It means N-dimensional array. One object has a shape, one data type for its elements and an index along each axis.
What is the difference between NumPy and Pandas?
NumPy works well with numerical arrays of a common type. Pandas DataFrames add column names and can hold different types in different columns. A project can use both.
How does broadcasting work?
NumPy checks axis lengths from the right. Equal lengths match, and a length of one can expand. A scalar can operate on every element.
Can NumPy calculate sample standard deviation?
Yes. Use np.std(values, ddof=1) for a sample with at least two observations. The default uses a divisor equal to the number of observations.
How do I reshape an array?
Use values.reshape(2, 3) for six elements arranged in two rows. You may supply −1 for one dimension to let NumPy infer its length.
What should I learn after NumPy?
Use Matplotlib to communicate a result and Pandas to attach dates or categories. If you want a credential after building a project, compare the Python certification options.
Explain an array result in your own words
Return to the club’s original puzzle. The warmest reading tells you when the peak occurred. Two weekly means tell you which week was warmer on average. Two standard deviations describe how tightly each week’s readings clustered. Keeping the days in order lets a reader see the late fall. These answers come from the same numbers because each calculation asks a different question.
For your own investigation, choose something you can observe consistently, write down the unit and predict one result by hand. Save the original array, the code, one labelled chart and a sentence about the limits of the evidence. Next, use the Pandas tutorial to attach dates and labels to measurements, or adapt one of the student data science projects to a question from your school.
Documentation used in this tutorial

