A one page reference to keep open while you work through the course. Each section is condensed; follow the links to the unit that explains it properly. Every snippet is a complete program that runs on Python 3.13 or newer, and the outputs shown come from CPython 3.15.
Literals and built in types
| Type | Literals | Mutable? | Notes |
|---|---|---|---|
int | 42, -7, 1_000_000, 0b1010, 0o17, 0xFF | no | unlimited size |
float | 3.14, .5, 1e-3, float("inf"), float("nan") | no | 64 bit binary; 0.1 + 0.2 != 0.3 |
complex | 2+3j | no | .real, .imag |
bool | True, False | no | a subclass of int |
NoneType | None | no | "no value"; test with is None |
str | 'hi', "hi", """several lines""", r"\d+", f"{x}" | no | Unicode text |
bytes | b"raw", b"\x00\xff" | no | binary data |
list | [], [1, "a"] | yes | ordered sequence |
tuple | (), (1,), (1, "a"), 1, "a" | no | the comma makes the tuple |
dict | {}, {"a": 1} | yes | keys keep insertion order |
set | set(), {1, 2} | yes | {} is an empty dict, not a set |
frozenset | frozenset({1, 2}) | no | hashable set |
range | range(5), range(1, 10, 2) | no | lazy sequence of ints |
Details: Values, names and types.
Conversions
| Expression | Result | Expression | Result |
|---|---|---|---|
int("42") | 42 | float("2.5") | 2.5 |
int(" 42\n") | 42 | int(3.9) | 3 (truncates) |
int("ff", 16) | 255 | int("4.2") | ValueError |
str(42) | '42' | repr("a") | "'a'" |
list("abc") | ['a', 'b', 'c'] | tuple([1, 2]) | (1, 2) |
set([1, 1, 2]) | {1, 2} | dict([("a", 1)]) | {'a': 1} |
chr(65) | 'A' | ord("A") | 65 |
hex(255), bin(5) | '0xff', '0b101' | bool("False") | True (nonempty) |
"é".encode("utf-8") | b'\xc3\xa9' | b'\xc3\xa9'.decode("utf-8") | 'é' |
Truthiness
Falsy: False, None, 0, 0.0, 0j, "", b"", [], (), {}, set(), range(0). Everything else is truthy, including "0", "False", " " and [0]. So if items: means "if the list isn't empty".
Operators and precedence
// rounds down (towards minus infinity) and % takes the sign of the divisor. round() sends halves to the nearest even number. and/or return one of their operands, not necessarily True or False. Details: Operators and expressions.
| Priority | Operators |
|---|---|
| highest | x[i], x[i:j], f(...), x.attr |
** (binds tighter than a unary minus on its left: -2 ** 2 is -4) | |
+x, -x, ~x | |
*, @, /, //, % | |
+, - | |
<<, >> | |
& | |
^ | |
| | |
comparisons: ==, !=, <, <=, >, >=, in, not in, is, is not | |
not | |
and | |
or | |
a if condition else b | |
lambda | |
| lowest | := |
When in doubt, add parentheses.
Indexing and slicing
seq[start:stop:step] includes start and excludes stop. An omitted start or stop means "from the beginning" or "to the end" (reversed when step is negative), and the step defaults to 1. An index out of range raises IndexError, but a slice out of range returns what exists. Slicing a list makes a new (shallow) list; lst[1:3] = [...] replaces that part in place.
Lists, tuples, dicts and sets
| List | Effect |
|---|---|
lst.append(x) / lst.extend(items) | add one item / all items at the end |
lst.insert(i, x) | insert before index i |
lst.pop() / lst.pop(i) | remove and return the last / the i-th item |
lst.remove(x) | remove the first x (ValueError if absent) |
del lst[i], del lst[i:j] | delete by index or slice |
lst.index(x), lst.count(x) | position of the first x; number of x |
lst.sort(key=..., reverse=True) | sort in place, returns None |
sorted(lst), reversed(lst) | new sorted list; reverse iterator |
lst.copy(), lst[:] | shallow copy |
| Dict | Effect |
|---|---|
d[key] | value, or KeyError if missing |
d.get(key, default) | value, or default (None if not given) |
d[key] = value | add or replace |
d.setdefault(key, default) | value, inserting default first if missing |
d.pop(key, default), del d[key] | remove a key |
d.keys(), d.values(), d.items() | live views |
key in d | checks keys, not values |
d | other, d |= other, d.update(other) | merge; the right side wins |
| Set | Effect |
|---|---|
s.add(x) | add an element |
s.discard(x) / s.remove(x) | remove; remove raises KeyError if absent |
a | b, a & b, a - b, a ^ b | union, intersection, difference, symmetric difference |
a <= b, a < b | subset, proper subset |
Tuples support indexing, slicing, count and index, and unpacking: first, *rest = (1, 2, 3).
Details: Collections and comprehensions.
Comprehensions
Generator expressions produce items one at a time, which saves memory; see Iterators and generators.
Decisions and loops
match (3.10+) compares a value against patterns:
| Pattern | Matches |
|---|---|
case 0:, case "on":, case None: | a literal value |
case x: | anything, binding it to x (a capture pattern) |
case [first, *rest]: | a sequence, unpacking it |
case {"id": key}: | a mapping that has that key (extra keys are allowed) |
case Point(x=0, y=y): | an instance of a class, checking attributes |
case "y" | "yes": | any of several patterns |
case n if n > 0: | a pattern plus a guard condition |
case _: | anything (the wildcard) |
Details: Control flow.
Defining functions
| Syntax | Meaning |
|---|---|
def f(a, b=2): | b has a default, evaluated once when def runs |
def f(a, /, b): | parameters before / are positional only |
def f(a, *, b): | parameters after * are keyword only |
def f(*args, **kwargs): | collect extra positional arguments into a tuple and keyword arguments into a dict |
f(*items, **mapping) | unpack a sequence and a dict into arguments at the call |
lambda x: x * 2 | a small anonymous function; use def if it needs a name |
def f(items=None): | the safe way to default to a new list: create it inside when items is None |
Details: Functions.
Exceptions
| Syntax | Meaning |
|---|---|
except (KeyError, IndexError) as err: | catch several types |
except Exception: | catch almost everything; never use a bare except: |
raise | inside except: reraise the current exception |
raise ConfigError("bad") from err | raise a new exception, chained to the original |
else: / finally: | runs if nothing was raised / runs in every case |
Common built in exceptions: ValueError (right type, bad value), TypeError (wrong type), KeyError, IndexError, AttributeError, NameError, ZeroDivisionError, FileNotFoundError. Details: Errors and exceptions.
with and files
with closes the file even if an error occurs. Always pass encoding="utf-8" for text. For CSV files also pass newline="".
| Mode | Meaning |
|---|---|
"r" | read (the default) |
"w" | write, emptying the file first |
"a" | append to the end |
"x" | create; fail if the file exists |
"b" | binary, added to another mode: "rb", "wb" |
"+" | read and write: "r+" |
Details: Files and data formats.
Imports
Put imports at the top of the file: standard library first, then third party packages, then your own modules. Avoid from module import *. Code under if __name__ == "__main__": runs only when the file is executed as a script, not when it is imported. Details: Modules and packages.
f-strings and the format spec
| Part of the spec | Meaning | Example |
|---|---|---|
<, >, ^ | align left, right, centre | {name:>8} |
| a character before the alignment | fill character | {name:*^8} |
| width | minimum width; numbers align right, text left | {price:8.3f} |
0 before the width | pad numbers with zeros | {42:05d} |
.N with f | N digits after the point | {price:.2f} |
, or _ | group thousands | {count:,} |
% | multiply by 100 and add % | {ratio:.1%} |
e | scientific notation | {1234.5:.2e} |
x, b, o; # | hex, binary, octal; # adds 0x, 0b, 0o | {255:#x} |
+ | always show the sign | {5:+} |
!r | use repr() instead of str() | {name!r} |
= after the expression | print the expression text too | {price=:.1f} |
Since 3.12, an f-string can reuse its own quote character inside the braces: f"{", ".join(names)}". Details: Strings and text formatting.
Essential builtins
| Built in | Use |
|---|---|
len(x) | number of items |
range(start, stop, step) | integers from start up to, not including, stop |
enumerate(items, start=0) | pairs of (index, item) |
zip(a, b, strict=True) | items side by side; strict=True (3.10+) raises if the lengths differ |
sorted(items, key=..., reverse=...) | a new sorted list; plain sorted puts capitals before lower case |
min(...), max(...) | smallest and largest; also take key= and default= |
sum(numbers, start=0) | total |
any(items), all(items) | is at least one truthy? are all truthy? (all([]) is True) |
isinstance(obj, cls) | type check that respects subclasses; cls may be a tuple |
abs, round, divmod, pow | arithmetic helpers |
print, input, open | console and file I/O |
type, id, dir, help | inspection |
Common string methods
| Method | Returns |
|---|---|
strip(), lstrip(), rstrip() | without surrounding whitespace (or the given characters) |
split(sep), split() | list of parts; with no argument, splits on runs of whitespace |
sep.join(strings) | the strings joined with sep between them |
replace(old, new, count) | a copy with replacements |
find(sub) / index(sub) | first position; find gives -1, index raises ValueError |
count(sub) | number of nonoverlapping occurrences |
startswith(prefix), endswith(suffix) | True/False; also accept a tuple of options |
lower(), upper(), title(), casefold() | case changes; casefold is for caseless comparison |
isdigit(), isalpha(), isalnum(), isspace() | character tests |
removeprefix(p), removesuffix(s) | without that prefix or suffix, if present (3.9+) |
partition(sep) | (before, sep, after) at the first sep |
zfill(width), center(width, fill) | padded copies |
splitlines() | list of lines without line endings |
Strings are immutable: every method returns a new string.
pathlib basics
| Expression | Meaning |
|---|---|
Path("data") / "raw" / "x.csv" | join path parts with /, on every operating system |
.name, .stem, .suffix, .parent | x.csv, x, .csv, data/raw |
.exists(), .is_file(), .is_dir() | tests |
.mkdir(parents=True, exist_ok=True) | create a folder and any missing parents |
.iterdir(), .glob("*.csv"), .rglob("*.py") | list a folder; match a pattern; match recursively |
.read_text(encoding="utf-8"), .write_text(text, encoding="utf-8") | whole file text I/O |
.unlink(missing_ok=True) | delete a file |
Path.cwd(), Path.home(), .resolve() | current folder, home folder, absolute path |
Topic selection inspired by Laurent Pointal's Python 3 Memento (CC BY 4.0); written fresh for this course.