Languages
Python Cheat Sheet — Syntax and Built-ins Reference
The Python 3 syntax and built-ins you reach for every day, from slicing and f-strings to comprehensions, classes, and context managers.
Put it into practice with the matching tool.
Run Python in the browser →Advertisement
Strings
f"Hi {name}, {n:.2f}"f-string with an embedded expression and format specs[1:4] s[::-1]Slice characters 1–3 / reverse a strings.split(",")Split into a list on a separator", ".join(items)Join a list of strings with a separators.strip()Remove leading and trailing whitespaces.replace("a", "b")Replace every occurrences.startswith("x")Prefix test (endswith for suffixes)s.lower() / s.upper()Change caseLists, tuples, and sets
xs.append(x)Add one item to the endxs.extend(ys)Add every item from another iterablexs.pop()Remove and return the last itemsorted(xs, key=len, reverse=True)Return a new sorted listlen(xs)Number of itemsa, b = b, aSwap two variables with tuple unpackingfirst, *rest = xsUnpack the head and the remaining itemsset(xs)Unique items; use | & - for union, intersection, differenceDictionaries
d.get("k", default)Read a key without raising KeyErrord.items()Iterate over (key, value) pairsd.setdefault("k", [])Insert a default if missing and return the value{**a, **b} / a | bMerge dicts (later keys win)"k" in dTest whether a key existsdel d["k"]Remove a keyComprehensions
[x * 2 for x in xs]List comprehension[x for x in xs if x > 0]Filter while building the list{k: v for k, v in pairs}Dict comprehension{x % 3 for x in xs}Set comprehensionsum(x * x for x in xs)Generator expression — lazy, no list builtControl flow
for i, x in enumerate(xs):Loop with an indexfor a, b in zip(xs, ys):Loop over two iterables in stepfor i in range(0, 10, 2):Loop over 0, 2, 4, 6, 8x if cond else yConditional expressionmatch cmd:
case "go": ...Structural pattern matching (3.10+)while (line := f.readline()):Walrus operator: assign inside an expressionFunctions and classes
def f(a, b=2, *args, **kwargs):Defaults, extra positional and keyword argumentslambda x: x + 1Anonymous one-expression functiondef f(x: int) -> str:Type hints (not enforced at runtime)class Dog(Animal):Define a class that inherits from Animaldef __init__(self, name):Constructor@dataclassAuto-generate __init__, __repr__, and __eq__@propertyExpose a method as a read-only attributeFiles and errors
with open("f.txt", encoding="utf-8") as f:Open a file and close it automaticallyf.read() / f.readlines()Read the whole file / a list of linesopen("f.txt", "w").write(s)Write text (mode "a" appends)try: ... except ValueError as e: ...Catch a specific exceptionfinally:Runs whether or not an exception occurredraise ValueError("bad input")Raise an exceptionimport json; json.loads(s)Parse JSON (json.dumps to serialise)