Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 2: Programming Toolkit

Python essentials for ML

P2.150 min●○○ BeginnerReviewed Dec 1, 2026

Why this matters for machine learning

Every ML tool in this course (NumPy, pandas, PyTorch) is used from Python, and the code you read and write is made of the same small set of pieces: values, lists, dictionaries, loops, functions and classes. Knowing them well means you can read other people's code and find your own bugs.

Before this: Your toolkit

After this lesson you can

  • Use Python's basic values (int, float, str, bool, None) and operators correctly, including /, // and %, and explain why 0.1 + 0.2 is not exactly 0.3
  • Explain that a variable is a name attached to an object, and use that to predict what happens with b = a, a copy and a deep copy
  • Build and read lists, tuples, dictionaries and sets, with indexing, slicing, unpacking and the usual methods
  • Write loops, functions (with default and keyword arguments, and without the mutable-default trap), comprehensions and a small class
  • Read a traceback from the last line upward, and use try and except for an error you expect
  • Use the everyday ML idioms: zip, enumerate, dict.items, sorted with a key, f-strings and import

In P0.4 you ran your first cells: print, a variable, a list, a NumPy array. That was just enough to start. Now we slow down and learn the language properly, because every later lesson in this part, and most of the code you will meet in ML, is made of a small set of Python pieces.

You do not need all of Python. You need a small set of ideas, and you need them to be solid. This lesson walks through them in the order that makes them easiest, always with a cell you can run. By the end you will build a tiny training and test split, a word counter and a classifier from scratch, using nothing but what is on this page.

How to use this page. Every box on this page starts fresh, as P0.4 explained, so each box defines what it needs. Edit the code and press Run again as often as you like: changing a value and re-running is the fastest way to learn. Outputs below each box are what you should see. (The first Run on a page downloads Python, about 6 MB, once.)

Values and types

Everything in Python is a value, and every value has a type. The five you need first:

TypeExampleWhat it is for in ML
int7, -3, 1000000counts: examples, epochs, batch size
float7.0, 0.001, 1e-4real numbers: learning rate, loss, accuracy
str"cat", '7'text: labels, words, file names
boolTrue, Falseyes or no: is this prediction correct?
NoneNone“no value”: a missing result, an option not set

type(v) tells you the type of v. Run this and compare each line with the value that made it:

Values and types

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

7 int
7.0 float
'7' str
True bool
None NoneType
3.5 3 1 1024
-4 1
13 5.0 34
2 True True
int
str

Read it line by line:

  • 7, 7.0 and '7' look alike and are three different things: an integer, a float and a piece of text. repr(v) shows a value the way you would type it, so the string shows its quotes.
  • Division has three forms. / always gives a float (7 / 2 is 3.5). // is floor division: it divides and rounds down (7 // 2 is 3). % is the remainder (7 % 2 is 1). ** is the power. Rounding down means toward minus infinity, so -7 // 2 is -4 and not -3. The pair always fits together: −7=(−4)×2+1-7 = (-4)\times 2 + 1, so -7 % 2 is 1, and the remainder is never negative when the divisor is positive.
  • Conversion is explicit: int("12") makes the number 12, float("2.5") makes 2.5, str(3) makes the text "3". Adding text to text joins them ("3" + "4" is "34").
  • True and False are numbers too: True + True is 2. This is handy, because the number of correct predictions is just the sum of a list of True and False.
  • == asks “are these equal?” (3 == 3.0 is True). For None you write is None, because there is only one None, and is checks “is this the very same object?”. Use == for values and is only for None.
  • Dynamic typing. The name v first points to an int and then to a string, and Python does not complain. The type belongs to the value, not to the name. This is flexible, and it also means type mistakes show up only when the code runs.

Integers in Python can be as large as memory allows (2 ** 100 prints all 31 digits), so integer arithmetic never overflows. Floats do not behave like that: they have limited precision. P1.G1 showed how a float is stored, and here is the everyday consequence:

Floats are approximate

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

0.30000000000000004
False
True

Python (like most languages, which use the same 64-bit floats, P1.G1) stores 0.1 as the closest number it can, and the closest number is not exactly 0.1. So never compare two floats with ==. Ask whether they are close: the difference is smaller than a tolerance. (math.isclose does this for you.) One more surprise: round(2.5) is 2 and round(3.5) is 4, because Python rounds exact halves to the even neighbour. And round(2.675, 2) is 2.67, not 2.68, because the float nearest to 2.675 is a hair below it.

Variables are names, not boxes

Here is the single most useful picture in this lesson. When you write

a = [1, 2, 3]

Python makes a list object in memory, and then attaches the name a to it, like a sticky note. The name is not the list, and the list is not stored “inside” a. Writing b = a attaches a second sticky note to the same object. It does not make a copy.

This does not matter for numbers and strings, because they cannot be changed in place. It matters a lot for lists, which can. Run this and watch which lines change together:

Two names, one list

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

[1, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3]
True False True
[[9, 0], [0, 0]] [[9, 0], [0, 0]] [[0, 0], [0, 0]]
[[1, 0], [1, 0]]
  • b.append(4) changed a too, because a and b are the same list. a is b is True. c is a copy, so it kept [1, 2, 3]. c == [1, 2, 3] is True because == asks whether two lists hold equal contents, while a is c is False because is asks whether they are the same object.
  • A shallow copy (grid.copy(), or grid[:], or list(grid)) makes a new outer list, but the inner lists are still shared. Changing grid[0][0] showed through in shallow. A deep copy (copy.deepcopy) copies everything inside too, so deep stayed zero.
  • The last line is a famous trap. [[0] * 2] * 2 repeats the same inner list twice, so setting one entry changes both rows. To make independent rows, use a comprehension (you will meet it soon): [[0] * 2 for _ in range(2)].

Intuition

Think of a name as a sticky note and an object as a thing on a table. b = a puts a second note on the same thing. A copy buys a second thing. Changing the thing (append) is seen through every note on it. Moving a note (b = [9]) changes only that note.

Where the picture breaks: numbers and strings cannot be changed in place, so notes on them behave as if each note had its own copy. Only changeable objects (lists, dicts, sets, and objects of your own classes) show the sharing.

Math

There is no new maths, but there is a cost to know. Reading a[i] takes the same time however long the list is. Asking x in a for a list has to look at the items one by one, so it grows with the length nn (we say O(n)O(n), P1.G4). Asking x in s for a set or a dict key is, on average, independent of the size (O(1)O(1)), because they use a hash table. That is why you turn a list into a set before you test membership many times. The measured numbers come with NumPy in P2.2 and with growth rates in P1.G4.

Code

Changing a list in place and building a new one look alike and are not the same. The difference is exactly the sticky-note picture.

In place or new object?

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

True
[1, 2] [1, 2, 3] False
[1, 2, 3] [1, 2, 3] True

id(x) is a number that identifies the object. b = b + [3] makes a new list, so a is safe. b += [3] extends the existing list in place, so a changes too. For numbers, += always makes a new value.

Strings and f-strings

A string is text in quotes (single or double, the same). You can index and slice it like a list ("hello"[1:3] is "el"), join pieces with +, repeat with *, and use methods such as .split(), .strip(), .upper(), .lower(), ",".join(items). A string cannot be changed in place; every method returns a new string.

The tool you will use every day is the f-string: put f before the quote and write any expression in braces. After a colon you can give a format: .2f means two digits after the point, .1% means percent with one digit, , adds thousands separators, >9 right-aligns in nine characters, and 04d pads an integer with zeros to width 4.

f-strings

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

model_A: accuracy 0.91
91.2% of 12,345 examples
[  model_A] [0003]
7
acc=0.91234

The last form, {acc=}, prints the expression and its value, which is a quick way to debug. Training logs in ML code are mostly f-strings like these.

Lists

A list is an ordered, changeable collection, written with square brackets. It can hold anything, even a mix of types, and even other lists. It is the workhorse of Python.

index      0    1    2    3    4
value     10   20   30   40   50
negative  -5   -4   -3   -2   -1
  • Indexing starts at 0: a[0] is the first item. A negative index counts from the end: a[-1] is the last.
  • Slicing a[start:stop:step] gives a new list from start up to, but not including, stop. Leave a part out to use the default: a[:2] is the first two, a[3:] is everything from index 3, a[::2] is every second item, a[::-1] is the list reversed. A slice never raises an error for going past the end.
  • Lists are changeable: a[0] = 99 replaces an item, a.append(x) adds one item at the end, a.extend([x, y]) adds each item of another list, and a.pop() removes and returns the last. len(a) is the length and x in a asks whether x is an item.
Lists: index, slice, change

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

10 50 40
[20, 30, 40] [10, 20] [40, 50]
[10, 30, 50] [50, 40, 30, 20, 10]
[99, 20, 30, 40, 50, 60, 70, 80] 8
True 2
9 [1, 2]
[1, 2, 3] None

Two things to notice in the last lines. append([1, 2]) added the list as one item (the length went from 8 to 9), while extend adds each of its items. And sorted(x) returns a new sorted list, while x.sort() sorts in place and returns None. A very common bug is writing x = x.sort(), which leaves x equal to None.

Tuples, dictionaries and sets

A tuple is like a list that cannot be changed: point = (3, 4). Use it for a fixed group of values, such as a shape (28, 28) or a pair (features, label). Unpacking splits a tuple (or list) into names: x, y = point. It gives the swap x, y = y, x, and first, *rest = [1, 2, 3, 4] puts the first item in first and all the others in rest.

A dictionary (dict) maps keys to values: {"ann": 31, "bo": 25}. Look up with d["ann"]; a missing key raises a KeyError, while d.get("dan") gives None and d.get("dan", 0) gives your default. Add or change with d["cy"] = 40. d.items() gives (key, value) pairs, d.keys() the keys and d.values() the values. Since Python 3.7 a dict keeps insertion order. Keys must be hashable, which in practice means unchangeable: strings, numbers and tuples of such values are fine; lists, sets and dicts are not.

A set keeps only distinct items and tests membership fast: {1, 2, 2, 3} is {1, 2, 3}. You can combine sets: & for items in both, | for items in either. A set has no useful order and no indexing (small whole numbers happen to print in order; do not rely on it); use sorted(s) when you need a list in order. The empty set is set(), because {} is an empty dict.

Tuples, dicts, sets

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

(3, 4) 4 3 1 [2, 3, 4]
None 0 True
ann 31
bo 25
cy 40
['ann', 'bo', 'cy'] [31, 25, 40]
[1, 2, 3] 3 True
{2} {1, 2, 3}
{(0, 1): 'a tuple works as a key'}

In ML code a dict is the usual home of settings ({"lr": 0.1, "epochs": 3}), vocabularies ({"the": 0, "cat": 1}), and results ({"loss": 0.4, "acc": 0.9}).

Control flow

if, elif, else choose a branch. for walks over anything you can loop over (a list, a string, a dict, a range). while repeats as long as a condition holds. break leaves a loop, continue skips to the next round. Python uses indentation (four spaces) to mark what is inside a block, so the spaces are part of the code, not style.

Three helpers for loops come up constantly:

  • range(n) counts 0,1,…,n−10, 1, \dots, n-1; range(a, b, step) counts from a up to but not including b.
  • enumerate(xs) gives (index, item) pairs, so you do not count by hand.
  • zip(xs, ys) pairs items from two lists, (xs[0], ys[0]), (xs[1], ys[1]), and so on. It stops at the shorter list, which can hide a length mismatch.

Conditions use truthiness: 0, 0.0, "", [], {} and None count as false, and almost everything else counts as true, so if items: means “if the list is not empty”.

Loops and branches

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

0 cat 0.9 sure
1 dog 0.4 no
2 cat 0.75 maybe
8
3 1.0
[0, 1, 2] [2, 5, 8]
False False False False False False True
[(1, 'a'), (2, 'b')]

The sum is 1+3+4=81 + 3 + 4 = 8: k = 2 was skipped by continue and the loop stopped at k = 5 by break. The while loop halved the loss 8→4→2→18 \to 4 \to 2 \to 1 and stopped when it was no longer above 1, so it ran 3 times. Beware: a while whose condition never turns false runs forever. (If a cell on this page seems stuck, reload the page.) Note the last test: [0] is a list with one item, so it counts as true even though that item is 0. Since Python 3.10, zip(xs, ys, strict=True) raises an error if the lengths differ.

Functions

A function packages a piece of code under a name so you can reuse it. def starts it, the parameters go in brackets, and return sends a value back.

  • A parameter can have a default: threshold=0.5. The caller may skip it.
  • Arguments can be passed by position, or by keyword (threshold=0.8), in any order. Keywords make calls readable, so ML libraries use them for nearly every setting.
  • A function with no return returns None. To return several values, return a tuple and unpack it: lo, hi = min_max(v).
  • Scope. Names made inside a function are local: they exist only during the call. Assigning to a name inside a function makes a new local name; it does not change a global name of the same spelling (unless you declare it global).
A function with a default

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

0.6666666666666666
1.0
0.6666666666666666

With the default threshold 0.5 the prediction 0.7 counts as “yes”, which is wrong, so 2 of 3 are right. With threshold 0.8 all three are right.

The mutable default trap

A default value is created once, when the def line runs, and then reused on every call. For a number or a string that is harmless. For a list or dict it is a classic bug: every call that uses the default shares the same list.

The mutable default trap

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

[1]
[1, 2]
[1]
[2]

The first function remembered the 1 from the first call. The fix is the standard pattern: default to None, and make the list inside the function.

*args, **kwargs, scope and lambda

Two short forms you will see in library code. *args collects extra positional arguments into a tuple, and **kwargs collects extra keyword arguments into a dict. At a call, * and ** do the opposite: they spread a list or a dict into arguments. A lambda is a function with no name written in one line: lambda v: v * v. It is used mostly as a short key= for sorting (below). If it needs more than one line, write a def.

*args, **kwargs, lambda, scope

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

(1, 2) {'lr': 0.1, 'epochs': 3}
(1, 2) {'lr': 0.1}
25 [1, -2, -3]
100 0

bump() returned 100 but the global count stayed 0. (Inside a function, a name you only read is looked up outside; a name you assign is local. Reading a name before you assign it inside the same function raises UnboundLocalError.)

Comprehensions

A list comprehension builds a list in one line: [expression for item in iterable if condition]. It reads like set-builder notation, “the squares of x for x in the list”. The if at the end keeps only some items. An if ... else ... placed before the for chooses between two values. The same idea with braces builds a dict ({k: v for ...}) or a set. With round brackets, as in sum(x * x for x in xs), it is a generator expression, which makes the items one at a time without building the whole list.

Comprehensions

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

[1, 4, 9, 16, 25, 36]
[2, 4, 6]
['odd', 'even', 'odd', 'even', 'odd', 'even']
{'cat': 0, 'dog': 1, 'fish': 2}
{3, 4}
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]
91

The dict line builds a vocabulary: each word gets a number, which is how text is turned into numbers for a model. The nested one (for a ... for b ...) reads left to right like two nested loops.

When a plain loop is clearer. A comprehension is for building one collection from another. If you need several steps, early exits, or side effects such as printing, write a normal for loop. A comprehension that does not fit on one line is usually a loop in disguise.

Classes

A class bundles data and the functions that work on it into one new kind of object. You write the recipe once (class Dataset:) and then make as many instances as you like. Three words to know:

  • __init__ runs when you create an instance. It sets up the instance’s attributes (its data), such as self.xs.
  • A method is a function inside the class. Its first parameter is self, the instance it was called on. You write ds.mean_label(), and Python passes ds in as self for you.
  • Special methods with double underscores let your object work with built-in syntax. __len__ makes len(obj) work. __getitem__ makes obj[i] work, and also lets you loop over the object.

Below is a tiny Dataset: a list of inputs and a list of labels, kept together. This is the same shape as a PyTorch Dataset (P2.7), which must define __getitem__ to fetch one example, and in practice also __len__, because a DataLoader and samplers use it to know how many examples there are.

A tiny Dataset class

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

3 (2.0, 1) 0.6666666666666666
1.0 0
2.0 1
3.0 1

ds[1] called __getitem__(1) and got the pair (2.0, 1). The for x, y in ds loop worked with no extra code: when an object has __getitem__ and no other way to loop, Python asks for item 0, 1, 2, … until it gets an IndexError. A class instance is a changeable object, so the sticky-note rule applies: two names for one dataset share it.

Errors and exceptions

You met NameError in P0.4. Python has many error types, and each one is a hint. When code fails, Python raises an exception, and the program stops, unless you catch it. Here are the ones you will see most:

  • IndexError: a list position that does not exist, such as [1, 2, 3][5].
  • KeyError: a dict key that is not there, such as {"a": 1}["b"].
  • TypeError: the wrong kind of value for an operation, such as "2" + 2, or changing a tuple.
  • ValueError: the right type but a bad value, such as int("abc").
  • AttributeError: an attribute or method that does not exist, such as None.append(1). Very often the value is None when you expected a list.
  • ZeroDivisionError: dividing by zero, 1 / 0.
  • UnboundLocalError: using a local name before it has a value (see the scope note above).

Reading a traceback

When an error escapes, Python prints a traceback: the chain of calls that led to it, oldest first, ending with the error line. This is a short program saved as train.py:

def mean(values):
    return sum(values) / len(values)

def report(batches):
    for b in batches:
        print(mean(b))

report([[1, 2, 3], []])

It prints 2.0 and then fails. Your computer shows this (the ^^^ marks depend on your Python version, and the file paths are your own):

Traceback (most recent call last):
  File "train.py", line 8, in <module>
    report([[1, 2, 3], []])
  File "train.py", line 6, in report
    print(mean(b))
  File "train.py", line 2, in mean
    return sum(values) / len(values)
ZeroDivisionError: division by zero

Read it from the bottom: the error type and message (ZeroDivisionError), then the line that raised it (line 2), then the lines above it, which are the callers. The line that raised the error is not always the line that is wrong: here mean did what it was told, and the real cause is that an empty batch [] was passed in at line 8. Ask “which value was unexpected, and where did it come from?”

try and except

try / except lets you handle an error you expect and can recover from. Name the error type, so you do not hide real bugs.

Catching errors

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

list index      IndexError
dict key        KeyError
str plus int    TypeError
bad int         ValueError
None method     AttributeError
divide by zero  ZeroDivisionError
tuple item      TypeError
caught: invalid literal for int() with base 10: 'abc'

(The tests are lambdas so each could be run inside the same try; normally you put the risky line itself in the try.) A few rules: catch the narrowest error you can name (except ValueError), and avoid a bare except: that swallows everything, including your typos. Use raise ValueError("message") to signal a problem yourself. For a bug, it is usually better to let the program stop with a clear traceback than to hide the error.

Modules, imports and type hints

A module is a file of Python code, and import brings it in. The standard library comes with Python and has tools you will use all the time: math (square roots, pi), random, collections (such as Counter), json, and itertools. There are three forms:

import math                      # use as math.sqrt(16)
import numpy as np               # a short name; everyone writes np
from collections import Counter  # bring in one name

Libraries outside the standard library (NumPy, pandas, PyTorch) must be installed first. On this site, NumPy is available and loads when your cell imports it. On your own computer you install packages with pip (P2.8).

Type hints are optional notes about the types a function expects: def mean(xs: list[float]) -> float:. Python does not enforce them when the code runs; they help readers and tools such as editors and type checkers. You will see them in most modern ML code, and you may skip them in your own small scripts.

Idioms you will see in ML code

A handful of patterns appear again and again. Recognising them makes other people’s code readable.

Everyday idioms

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

4.0 3.1416
[('the', 3), ('and', 2)]
3 0
[('ann', 3.9), ('cy', 3.7), ('bo', 3.2)]
('ann', 3.9)
True True
  • for x, y in zip(xs, ys): walks two lists together (features and labels, predictions and targets).
  • for i, item in enumerate(items): gives a counter for free (start=1 to count from 1).
  • for key, value in d.items(): walks a dict.
  • sorted(items, key=..., reverse=True) sorts by any rule: the key function turns each item into the value to compare. max(items, key=...) and min take the same key. This is how you find the class with the highest score.
  • Counter counts items (a missing item counts 0, with no KeyError), and .most_common(k) lists the top kk.
  • any(...) and all(...) ask whether some, or every, item passes a test.
  • sum(...), min(...), max(...), len(...) work on any list of numbers.

Where plain lists stop

Lists hold numbers too, but they are not made for number crunching. + joins lists and * repeats them, so they do not add or multiply entries, and you need a loop or a comprehension for the maths. Even the dot product of P1.B3 needs zip:

Lists are not vectors

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

[3, 1, 1, 2.5]
[3, 1, 3, 1]
5.5

That 5.5 is the same dot product as in P1.B3. It works, but each number is a separate Python object, and a loop in Python does one step at a time. For arrays of thousands or millions of numbers this gets slow. NumPy (P2.2) stores numbers in one block, does a * b and a @ b in a single operation, and is the tool for arrays. Keep lists and dicts for what they are good at: records, words, settings, results.

Go deeper Iterators and generators: how loops get their items

A for loop asks its object for an iterator, and then asks that iterator for one item at a time. A generator function is a function that uses yield instead of return: it hands out one item, pauses, and continues when asked for the next. Nothing is computed until the loop asks. This is how data loaders hand out one batch at a time without holding every batch in memory.

def batches(items, size):
    for start in range(0, len(items), size):
        yield items[start:start + size]

for b in batches([1, 2, 3, 4, 5], 2):
    print(b)
[1, 2]
[3, 4]
[5]

A generator can be used only once: after it is used up, looping over it again gives nothing. g = (x * x for x in range(3)) is a generator, and list(g) gives [0, 1, 4] the first time and [] the second time. A list, by contrast, can be looped over again and again.

Go deeper Files, the with statement and other things left for later

On your own computer you read a file with with open("data.txt") as f:; the with block closes the file for you when it ends. Cells on this site have no files of yours to read, so the lessons here keep their data in the code. Other topics that are useful but not needed yet: global and nonlocal (changing a name from an outer scope), decorators (the @something line above a function), dataclasses (a short way to write classes that mostly hold data), and virtual environments (P2.8).

Bugs that catch every beginner

  • b = a and then changing b: you see a changed too. Fix: b = a.copy(), or copy.deepcopy(a) for nested lists.
  • [[0] * n] * m for a grid: you see changing one row changes all. Fix: [[0] * n for _ in range(m)].
  • def f(x, bag=[]): you see the list remembers earlier calls. Fix: default None, make the list inside.
  • x = x.sort(): you see x is None. Fix: x.sort() alone, or x = sorted(x).
  • looping twice over a generator: you see the second loop does nothing. Fix: make a list first, or build the generator again.
  • 0.1 + 0.2 == 0.3: you see False. Fix: compare with a tolerance (math.isclose).
  • 7 / 2 when you wanted whole numbers: you see 3.5. Fix: 7 // 2 for floor division.
  • zip of two lists of different length: you see the extra items vanish silently. Fix: check len, or zip(..., strict=True).
  • "2" + 2: you see TypeError. Fix: convert: int("2") + 2.
  • d["missing"]: you see KeyError. Fix: d.get("missing", default).
  • indentation off by one space: you see IndentationError, or code in the wrong block. Fix: four spaces for each level, always.

Practice: in-browser exercises

Each task has a short cell, the output to aim for, and a hidden answer. Write your own solution first. Then press Run and compare the output with the one shown.

1. f-strings. correct is 87 and total is 120. Print the accuracy as a percent with one decimal.

Practice 1: format a percent

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

Expected output: Accuracy: 72.5%

Show answerprint(f"Accuracy: {correct / total:.1%}"). The format .1% multiplies by 100, adds the percent sign and keeps one digit after the point.

2. Slicing. For a = list(range(10, 20)), print the last three items and then every second item from the start.

Practice 2: slices

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

Expected output:

[17, 18, 19]
[10, 12, 14, 16, 18]
Show answerprint(a[-3:]) and print(a[::2]).

3. Counting with a dict. Count how many times each letter appears in "banana", without Counter.

Practice 3: count letters

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

Expected output: {'b': 1, 'a': 3, 'n': 2}

Show answer
counts = {}
for ch in "banana":
    counts[ch] = counts.get(ch, 0) + 1
print(counts)

counts.get(ch, 0) gives 0 for a letter not seen yet, so there is no KeyError. The keys appear in the order the letters were first seen.

4. A function and a comprehension. Write normalize(xs) that rescales a list to the range 0 to 1: subtract the smallest value and divide by (largest minus smallest).

Practice 4: min-max scaling

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

Expected output: [0.0, 0.25, 0.5, 1.0]

Show answer
def normalize(xs):
    lo, hi = min(xs), max(xs)
    return [(x - lo) / (hi - lo) for x in xs]

With lo = 2 and hi = 10, the value 4 becomes (4−2)/8=0.25(4-2)/8 = 0.25. If every value is the same, hi - lo is 0 and you get a ZeroDivisionError: real code must decide what to do then.

5. A class. Write a class RunningMean with a method add(x) that remembers the total and the count, and a method mean(). Add 2, 4 and 9.

Practice 5: a small class

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

Expected output: 3 5.0

Show answer
class RunningMean:
    def __init__(self):
        self.total = 0.0
        self.count = 0

    def add(self, x):
        self.total += x
        self.count += 1

    def mean(self):
        return self.total / self.count

The attributes total and count live on the instance (self), so they survive between calls of add. This is the same idea as keeping a running average of the loss during training.

6. Find the bug. The goal is to keep the original order in backup and sort scores. The output should be [3, 1, 2] [1, 2, 3]. Run it as it is first, and look at what it prints.

Practice 6: fix the aliasing bug

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

Expected output after the fix: [3, 1, 2] [1, 2, 3]

Show answerThe buggy version prints [1, 2, 3] [1, 2, 3], because backup = scores is a second name for the same list, and sort() changes the list in place. Change the second line to backup = scores.copy().

Mini project: a tiny word classifier

Now put the pieces together. This program has a class that holds labelled text reviews, a train and test split, a word counter and a classifier made only of lists, dicts and functions. The idea of the classifier: count how often each word appears in positive and in negative reviews, and score a new text by adding, for each of its words, (positive count minus negative count). A positive total says “positive”.

Mini project

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

10 8 2
overlap: set()
positive: [('great', 3), ('loved', 2), ('acting', 2)]
negative: [('boring', 2), ('slow', 2), ('not', 2)]
'great fun'      -> 1
'slow and bad'   -> 0
'loved it'       -> 1

What each part did:

  • TextDataset is the Dataset idea again, with __len__ and __getitem__, plus a split method that shuffles the positions (not the data), takes the first part as the test set and the rest as the training set. Shuffling before splitting stops the split from depending on how the file was ordered. The two parts do not overlap, as overlap: set() confirms. P3.A4 explains why we hold out test data.
  • word_counts loops over the data and uses Counter.update to add the words of each matching review. pos[w] for a word never seen gives 0.
  • predict is a sum over a generator expression. 1 if score > 0 else 0 is a one-line if.
  • The seed makes the shuffle repeatable (P1.G3), but Python does not promise the same shuffle across versions. So the program prints only what never depends on the shuffle (the sizes and the overlap), and the counts and predictions use all ten reviews.

Do not do this in a real project: see Exercise 8. This is a toy, and an honest one: the classifier was counted on all ten reviews and then tried on texts, so it says nothing about how it would do on new data. The next step, which is Exercise 8, is to count on train only and measure on test.

Common misconceptions

Check yourself

Check your understanding

  1. After a = [1, 2, 3], b = a and b.append(4), what is a?

  2. A function is defined as def add(x, bag=[]): bag.append(x); return bag. What does the second call add(2) return, if the first call was add(1)?

  3. What does -7 // 2 give in Python?

  4. Which of these can be used as a key in a dict?

  5. What does list(zip([1, 2, 3], ["a", "b"])) give?

  6. You write a class with the methods __len__ and __getitem__. Which statements now work on an instance ds?

Exercises

Try each one in a box first. Then open the answer.

  1. For a = [5, 6, 7, 8, 9], what are a[-2], a[1:3] and a[::-1][:2]?
    Show answer8, [6, 7] and [9, 8]. The reversed list is [9, 8, 7, 6, 5], and its first two items are 9 and 8.
  2. What does this print: x = [1, 2], y = x, y += [3], z = x + [4], print(x, y, z)?
    Show answer[1, 2, 3] [1, 2, 3] [1, 2, 3, 4]. The += extended the shared list in place, so x changed, and x + [4] built a new list in z.
  3. Write count_labels(labels) that returns a dict of how often each label occurs. For ["cat", "dog", "cat"] it should give {'cat': 2, 'dog': 1}.
    Show answerLoop over the labels and use counts[lab] = counts.get(lab, 0) + 1, then return counts. (collections.Counter does the same.)
  4. From words = ["a", "tree", "is", "green"], build a dict from each word to its length, keeping only words longer than 3 letters.
    Show answer{w: len(w) for w in words if len(w) > 3} gives {'tree': 4, 'green': 5}.
  5. mean([]) crashes with ZeroDivisionError. Change mean so it returns None for an empty list.
    Show answerif not xs: return None before the division, because an empty list is false. Then mean([1, 2, 3]) is 2.0 and mean([]) is None. Whoever calls it must then handle None, or you meet an AttributeError or a TypeError later.
  6. Add a method batches(size) to the Dataset class that returns a list of lists, each with at most size examples. For 3 examples and size=2 the result is [[(1.0, 0), (2.0, 1)], [(3.0, 1)]].
    Show answerreturn [[self[i] for i in range(s, min(s + size, len(self)))] for s in range(0, len(self), size)]. The outer loop steps through the starting positions 0, 2, …; min(...) stops the last batch at the end of the data. A data loader (P2.7) does this idea for you.
  7. In the traceback shown earlier, the error is raised in mean on line 2. Which line would you change to fix the bug, and why?
    Show answerIt depends on what you want. The data contained an empty batch [] (line 8). Either remove empty batches where the data is made, or make mean handle an empty list on purpose. The line that raises an error is where Python noticed the problem, and the cause can be earlier.
  8. Extend the mini project: count words on train only, then measure the fraction of test texts that predict gets right. Is the number reliable with a test set of two?
    Show answerUse pos = word_counts(train, 1) and neg = word_counts(train, 0), then sum(predict(t, pos, neg) == y for t, y in test) / len(test). With two test items the accuracy can only be 0, 0.5 or 1, so one example changes it by 50 percentage points: it is far too noisy to trust. Real projects use much more data, and the number can change with the seed of the shuffle (P1.G3).
Go deeper Inheritance: a class built from another class

Inheritance makes a new class that starts as a copy of another and changes a little. super().__init__(...) calls the parent’s set-up. It is common in PyTorch, where your model inherits from nn.Module (P2.7), and otherwise best used sparingly.

class ScaledDataset(Dataset):
    def __init__(self, xs, ys, factor):
        super().__init__([x * factor for x in xs], ys)

sd = ScaledDataset([1.0, 2.0, 3.0], [0, 1, 1], 10)
print(sd[1], sd.mean_label(), isinstance(sd, Dataset))
(20.0, 1) 0.6666666666666666 True

isinstance(obj, Class) asks whether an object belongs to a class, or to a class built from it.

Key takeaways

  • Values have types (int, float, str, bool, None). Python decides the type of a value when the code runs, and a name can be moved to a value of another type. / always gives a float, // rounds down (so -7 // 2 is -4) and % is the matching remainder.
  • A variable is a name attached to an object, and it is not a box that holds a copy. After b = a both names point to one list, so changing it through b changes a. Use a.copy() or a[:] for a new list, and copy.deepcopy when the list holds lists.
  • A list is ordered and changeable, a tuple is ordered and fixed, a dict maps keys to values (and keeps insertion order), and a set keeps distinct items. Slicing a[start:stop:step] stops before stop, and negative indexes count from the end.
  • Control flow: if/elif/else, for over any iterable (with range, enumerate and zip), while, break and continue. Empty things (0, 0.0, an empty string, list, dict, and None) count as False.
  • A function takes parameters, can give defaults and keyword arguments, and returns a value (None if there is no return). A default is made once, when the function is defined, so never use a list or a dict as a default: use None and make the list inside.
  • A comprehension builds a list, dict or set in one line: [f(x) for x in xs if keep(x)]. A class bundles data with methods. The methods __len__ and __getitem__ make an object work with len(obj) and obj[i], which is the shape of a PyTorch Dataset.
  • Read an error from the last line upward. The type (KeyError, IndexError, TypeError, ValueError, ...) says what went wrong, and the lines above say where. Use try and except only for errors you expect and can handle.
  • Plain Python lists are flexible but slow for large amounts of numbers, so numeric work moves to NumPy arrays (P2.2). The structures in this lesson still hold your data, configuration and results.
Found a mistake? Tell us