Skip to content
Unit 2 of 28

Python cheat sheet

Contents · 16

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

TypeLiteralsMutable?Notes
int42, -7, 1_000_000, 0b1010, 0o17, 0xFFnounlimited size
float3.14, .5, 1e-3, float("inf"), float("nan")no64 bit binary; 0.1 + 0.2 != 0.3
complex2+3jno.real, .imag
boolTrue, Falsenoa subclass of int
NoneTypeNoneno"no value"; test with is None
str'hi', "hi", """several lines""", r"\d+", f"{x}"noUnicode text
bytesb"raw", b"\x00\xff"nobinary data
list[], [1, "a"]yesordered sequence
tuple(), (1,), (1, "a"), 1, "a"nothe comma makes the tuple
dict{}, {"a": 1}yeskeys keep insertion order
setset(), {1, 2}yes{} is an empty dict, not a set
frozensetfrozenset({1, 2})nohashable set
rangerange(5), range(1, 10, 2)nolazy sequence of ints

Details: Values, names and types.

Conversions

ExpressionResultExpressionResult
int("42")42float("2.5")2.5
int(" 42\n")42int(3.9)3 (truncates)
int("ff", 16)255int("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.

PriorityOperators
highestx[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

Indexing and slicing lst = [10, 20, 30, 40, 50]

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

ListEffect
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
DictEffect
d[key]value, or KeyError if missing
d.get(key, default)value, or default (None if not given)
d[key] = valueadd 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 dchecks keys, not values
d | other, d |= other, d.update(other)merge; the right side wins
SetEffect
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 ^ bunion, intersection, difference, symmetric difference
a <= b, a < bsubset, 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:

PatternMatches
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

SyntaxMeaning
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 * 2a 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

SyntaxMeaning
except (KeyError, IndexError) as err:catch several types
except Exception:catch almost everything; never use a bare except:
raiseinside except: reraise the current exception
raise ConfigError("bad") from errraise 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="".

ModeMeaning
"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 specMeaningExample
<, >, ^align left, right, centre{name:>8}
a character before the alignmentfill character{name:*^8}
widthminimum width; numbers align right, text left{price:8.3f}
0 before the widthpad numbers with zeros{42:05d}
.N with fN digits after the point{price:.2f}
, or _group thousands{count:,}
%multiply by 100 and add %{ratio:.1%}
escientific notation{1234.5:.2e}
x, b, o; #hex, binary, octal; # adds 0x, 0b, 0o{255:#x}
+always show the sign{5:+}
!ruse repr() instead of str(){name!r}
= after the expressionprint 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 inUse
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, powarithmetic helpers
print, input, openconsole and file I/O
type, id, dir, helpinspection

Common string methods

MethodReturns
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

ExpressionMeaning
Path("data") / "raw" / "x.csv"join path parts with /, on every operating system
.name, .stem, .suffix, .parentx.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.