NumPy

scientific-python
Use arrays, shapes, indexing, and vectorized operations for numerical data.
  • Level: Beginner to intermediate
  • Estimated time: 35–50 minutes
  • You will learn: Use arrays, shapes, indexing, and vectorized operations for numerical data.
  • Practice in: Jupyter or Google Colab

Questions

  • What problem does NumPy help us solve in a small Python program?
  • What should we predict before running the example?
  • What value, output, or error should we inspect after changing one line?

Objectives

  • Run a complete example for NumPy arrays in Colab.
  • Explain the example line by line using plain language.
  • Change one part of the code and predict the result before running it.
  • Recognize one common mistake and use the error message as evidence.

Hands-on episode: NumPy

A NumPy array stores values of a common numerical type and supports vectorized operations, shapes, axes, and numerical indexing.

We will learn this by running code, not by memorizing a definition first. Open the Colab notebook from the button above, find this section, and run each cell in order. Keep a small note beside the notebook with three columns: prediction, actual result, and what changed.

Example 1.1

Predict the result of adding 10 to every temperature.

import numpy as np

celsius = np.array([0, 10, 20])
fahrenheit = celsius * 9 / 5 + 32
print(fahrenheit)

Run the cell once without editing it. If the result is different from your prediction, leave the prediction visible and write one sentence about the difference. That sentence is more useful than a perfect first guess.

Explain Example 1.1

  • The array stores three temperatures as one numerical object.
  • The multiplication and division happen element by element without a manual loop.
  • Adding 32 also happens to every element, producing a new array.

Now explain the example out loud or in a Markdown cell. Use short sentences: “this line creates…”, “this name stores…”, “this output appears because…”. If you cannot explain a line yet, run only the lines above it and inspect the values that exist at that moment.

Challenge 1.1

NoteChallenge

Try the same expression with a plain Python list. The behavior is different because lists and arrays define operations differently. This comparison explains why NumPy exists.

Show a safe way to approach the challenge
  1. Copy Example 1.1 into a new Colab cell.
  2. Change exactly one value, name, condition, or line.
  3. Write the expected output before running the cell.
  4. Run the cell and compare the actual result with your prediction.
  5. If the result surprises you, undo the change and try a smaller one.

Suggested first move: Try the same expression with a plain Python list.

Debugging checkpoint 1.1

WarningDebugging checkpoint

Shape mismatch is a common NumPy error. When an operation fails, print .shape for each array before changing code. For axis confusion, say whether you want to summarize across rows or down columns before choosing the axis.

Do not debug by rewriting the whole example. Read the error type or surprising output, inspect the closest value with print(...) or type(...), then change one thing. This is the same routine you will use in larger projects.

Apply it

Create an array of five temperatures, convert them, compute the mean, subtract the mean, and explain what each resulting number represents.

Finish by adding a Markdown cell that answers: What did this example teach me that I can reuse in a project?

Key points

  • Learn the concept by running a complete, small example first.
  • Predict before execution so your thinking becomes visible.
  • Change one thing at a time so cause and effect stay clear.
  • Treat errors as clues about the exact line or value Python could not handle.

Why this matters

Use arrays, shapes, indexing, and vectorized operations for numerical data.

This lesson combines related subtopics that belong together in one learning conversation. You will still pause for a quiz after each section, but you do not need to jump between separate pages while building one clear explanation.

NoteGuiding questions

By the end of this lesson, you should be able to answer:

  • How do the sections in NumPy fit together?
  • Which small example demonstrates each section?
  • Which debugging clue should I check first for each section?
NoteLearning objectives

You will practice how to:

  • explain the shared concept for this lesson;
  • use each section as one step in a larger workflow;
  • complete 3 short section quizzes before moving on;
  • connect examples, mistakes, and debugging routines.

Lesson map

  • 1. NumPy Arrays — Use NumPy arrays for efficient numerical data.
  • 2. NumPy Indexing and Shapes — Read array dimensions and select rows, columns, and slices.
  • 3. Vectorized Operations — Apply operations to whole arrays without manual Python loops.

1. NumPy Arrays

Use NumPy arrays for efficient numerical data.

TipAnalogy

A NumPy array is like a tray of identical measuring cups arranged in rows and columns.

What this means

A NumPy array stores same-type numerical values in a shape that supports fast operations.

Example 1

Predict what will happen before you run the code.

import numpy as np

values = np.array([1, 2, 3])
print(values * 10)

Step-by-step explanation

  1. import numpy as np — pause here and say what this line reads, creates, changes, or displays.
  2. values = np.array([1, 2, 3]) — pause here and say what this line reads, creates, changes, or displays.
  3. print(values * 10) — pause here and say what this line reads, creates, changes, or displays.

After running the example, compare the actual output with your prediction. If they differ, do not erase your prediction. The difference is the part that can teach you the most.

Challenge

NotePractice

Change one input value, predict the new output, run the code, and explain the difference in one sentence.

Show one possible solution path
  1. Copy Example 1 into Colab, Jupyter, or a .py file.
  2. Mark the line you plan to change.
  3. Write a one-sentence prediction.
  4. Run the changed code.
  5. If the result surprises you, restore the original and change a smaller part.

The goal is not to find the only correct answer. The goal is to create a small experiment where you can explain cause and effect.

Common mistakes

WarningCommon mistake

NumPy arrays and Python lists look similar but operations behave differently. [1,2]2 repeats; np.array([1,2])2 multiplies.

When you get stuck, use this debugging routine:

  1. Read the last line of the error message or inspect the unexpected output.
  2. Find the smallest line of code that could be responsible.
  3. Print or inspect the value and type at that point.
  4. Change one thing.
  5. Run again and record what changed.

Check your understanding

This quiz checks the ideas in this section before you move on.

2. NumPy Indexing and Shapes

Read array dimensions and select rows, columns, and slices.

TipAnalogy

Shape is the layout of a theater, and indexing chooses seats by row and column.

What this means

Shape describes array dimensions; indexing selects parts of the array.

Example 2

Predict what will happen before you run the code.

import numpy as np

grid = np.array([[1, 2, 3], [4, 5, 6]])
print(grid.shape)
print(grid[1, 2])

Step-by-step explanation

  1. import numpy as np — pause here and say what this line reads, creates, changes, or displays.
  2. grid = np.array([[1, 2, 3], [4, 5, 6]]) — pause here and say what this line reads, creates, changes, or displays.
  3. print(grid.shape) — pause here and say what this line reads, creates, changes, or displays.
  4. print(grid[1, 2]) — pause here and say what this line reads, creates, changes, or displays.

After running the example, compare the actual output with your prediction. If they differ, do not erase your prediction. The difference is the part that can teach you the most.

Challenge

NotePractice

Change one input value, predict the new output, run the code, and explain the difference in one sentence.

Show one possible solution path
  1. Copy Example 1 into Colab, Jupyter, or a .py file.
  2. Mark the line you plan to change.
  3. Write a one-sentence prediction.
  4. Run the changed code.
  5. If the result surprises you, restore the original and change a smaller part.

The goal is not to find the only correct answer. The goal is to create a small experiment where you can explain cause and effect.

Common mistakes

WarningCommon mistake

A 2D NumPy array often uses array[row, column], not two separate list indexes.

When you get stuck, use this debugging routine:

  1. Read the last line of the error message or inspect the unexpected output.
  2. Find the smallest line of code that could be responsible.
  3. Print or inspect the value and type at that point.
  4. Change one thing.
  5. Run again and record what changed.

Check your understanding

This quiz checks the ideas in this section before you move on.

3. Vectorized Operations

Apply operations to whole arrays without manual Python loops.

TipAnalogy

Vectorization is like stamping every envelope with one press instead of writing each stamp by hand.

What this means

Vectorization lets library code apply an operation across many values efficiently.

Example 3

Predict what will happen before you run the code.

import numpy as np

temperatures_c = np.array([0, 10, 20])
temperatures_f = temperatures_c * 9 / 5 + 32
print(temperatures_f)

Step-by-step explanation

  1. import numpy as np — pause here and say what this line reads, creates, changes, or displays.
  2. temperatures_c = np.array([0, 10, 20]) — pause here and say what this line reads, creates, changes, or displays.
  3. temperatures_f = temperatures_c * 9 / 5 + 32 — pause here and say what this line reads, creates, changes, or displays.
  4. print(temperatures_f) — pause here and say what this line reads, creates, changes, or displays.

After running the example, compare the actual output with your prediction. If they differ, do not erase your prediction. The difference is the part that can teach you the most.

Challenge

NotePractice

Change one input value, predict the new output, run the code, and explain the difference in one sentence.

Show one possible solution path
  1. Copy Example 1 into Colab, Jupyter, or a .py file.
  2. Mark the line you plan to change.
  3. Write a one-sentence prediction.
  4. Run the changed code.
  5. If the result surprises you, restore the original and change a smaller part.

The goal is not to find the only correct answer. The goal is to create a small experiment where you can explain cause and effect.

Common mistakes

WarningCommon mistake

Vectorized expressions still need matching shapes. Shape mismatches are clues, not random failures.

When you get stuck, use this debugging routine:

  1. Read the last line of the error message or inspect the unexpected output.
  2. Find the smallest line of code that could be responsible.
  3. Print or inspect the value and type at that point.
  4. Change one thing.
  5. Run again and record what changed.

Check your understanding

This quiz checks the ideas in this section before you move on.

Notebook and Colab practice

Open a blank notebook at https://colab.new. Use one section at a time: copy the Example 1, predict the result, run it, answer the section quiz, and then move to the next section. This is better than copying the entire page at once.

Instructor note

Teaching notes
  • Treat each section as a short teaching episode.
  • Pause for the section quiz before introducing the next section.
  • Ask learners to compare sections: what stayed the same, and what changed?
  • If time is short, teach the first two sections live and assign the rest as practice.

Key points

TipKey points
  • NumPy Arrays: A NumPy array stores same-type numerical values in a shape that supports fast operations.
  • NumPy Indexing and Shapes: Shape describes array dimensions; indexing selects parts of the array.
  • Vectorized Operations: Vectorization lets library code apply an operation across many values efficiently.
  • Use the section quizzes as gates: review before moving on if a quiz feels uncertain.

References

  • NumPy documentation: https://numpy.org/doc/stable/
  • Matplotlib documentation: https://matplotlib.org/stable/
  • SciPy documentation: https://docs.scipy.org/doc/scipy/
  • SymPy documentation: https://docs.sympy.org/
  • Python Tutorial: https://docs.python.org/3/tutorial/
  • Quarto OJS documentation: https://quarto.org/docs/interactive/ojs/
  • ipywidgets documentation: https://ipywidgets.readthedocs.io/en/stable/
Back to top