Skip to content
Chapter 2 of 8

Lists and loops: many values at once

Machine learning is lists of numbers, everywhere. So the next skill is handling many values at once. A list is an ordered sequence. A for loop visits each item. A comprehension builds a new list from an old one in a single readable line. Master these three and you can express almost any data transformation you will meet later, from a sequence of tokens to a row of model weights.

The lab: read it, then run it

labs/foundations/f2-lists-loops.py
#!/usr/bin/env python3
"""
LAB F2: Lists and loops. Working with many values at once.

Machine learning is lists of numbers all the way down. Here you build lists, walk
them with loops, transform them with comprehensions, and prove the results. This
is the muscle you use in every later lab.

Run: python3 modules/academy-content/labs/foundations/f2-lists-loops.py
"""
import sys

# STEP 1: a list holds an ordered sequence of values.
nums = [4, 8, 15, 16, 23, 42]
print("STEP 1: a list")
print(f"  nums = {nums}   (length {len(nums)})")

# STEP 2: a for loop visits every item in turn.
running_total = 0
for n in nums:
    running_total += n
print("")
print("STEP 2: sum with a loop")
print(f"  total = {running_total}")

# STEP 3: a comprehension builds a new list from an old one, in one line.
doubled = [n * 2 for n in nums]
evens = [n for n in nums if n % 2 == 0]
print("")
print("STEP 3: transform and filter with comprehensions")
print(f"  doubled = {doubled}")
print(f"  evens   = {evens}")

# STEP 4: invariants. The sum matches Python's own sum(), and doubling then
# halving returns the original list. If either fails, the logic is wrong.
ok = (running_total == sum(nums)) and ([d // 2 for d in doubled] == nums)
print("")
print(f"STEP 4: loop-sum matches sum(), and double-then-halve round-trips: {'YES' if ok else 'NO'}")
if not ok:
    sys.exit(1)
print("")
print("Lists and loops are the workhorse of ML code. Next: functions and dictionaries.")
Runnable lab
f2-lists-loops.py

Sum a list with a loop, then transform and filter it with comprehensions.

Proves: loop-sum matches sum(), and double-then-halve round-trips: YES

Open the notebook

Runs in your browser via Pyodide. First run loads the runtime once; no install, no server.

You summed with a loop, then reshaped the list two ways in one line each. The round-trip check (double then halve returns the original) is the kind of invariant that catches bugs before they cost you hours. Next: functions and dictionaries, where you build your first piece of a language model.
Check your understanding
  1. 1. What does a for loop do with a list?

  2. 2. What is a list comprehension?

  3. 3. Why check that double-then-halve returns the original list?