Beginner

Python Cheatsheet

A dense quick-reference for Python 3.12+ syntax, collections, comprehensions, classes, error handling, async, and tooling commands.

SyntaxData StructuresAsyncTyping
NotesCheatsheet

Variables & Types

x = 10            # int (arbitrary precision)
pi = 3.14         # float
name = "Ada"      # str (immutable)
flag = True       # bool
nothing = None    # NoneType
a, b = 1, 2       # unpacking
big = 1_000_000   # digit separators

type(x)           # <class 'int'>
int("42"); float("3.14"); str(42)
isinstance(x, int)

Strings & f-strings

s = "Hello, World"
f"{name} is {age}"          # interpolation
f"{value:.2f}"              # 2 decimals
f"{n:,}"                    # thousands sep
f"{x=}"                     # debug: x=10
f"{val!r}"                  # repr()

s.upper(); s.lower(); s.strip()
s.split(","); ",".join(items)
s.replace("a", "b")
s.startswith("He"); "ell" in s
s[0]; s[-1]; s[1:4]; s[::-1]  # slicing
"".join(reversed(s))

Collections

List

xs = [1, 2, 3]
xs.append(4); xs.extend([5, 6])
xs.insert(0, 9); xs.pop(); xs.remove(2)
xs.sort(reverse=True); xs.reverse()
sorted(xs, key=len); len(xs)
first, *rest = xs

Dict

d = {"a": 1, "b": 2}
d["c"] = 3
d.get("z", 0)               # default if missing
d.setdefault("k", [])
d.keys(); d.values(); d.items()
merged = d | {"e": 5}       # merge (3.9+)
for k, v in d.items(): ...

Tuple & Set

t = (1, 2, 3)               # immutable
s = {1, 2, 3}               # set
s.add(4); s.discard(1)
s1 & s2; s1 | s2; s1 - s2   # intersect/union/diff

Comprehensions

[n * n for n in range(10)]
[n for n in xs if n > 0]
{k: v for k, v in pairs}
{len(w) for w in words}
(n for n in range(1000))    # lazy generator

Functions

def f(a, b=0, *args, key=None, **kwargs):
    return a + b

square = lambda n: n * n
sorted(xs, key=lambda x: x.name)

# generic (3.12+)
def first[T](xs: list[T]) -> T | None:
    return xs[0] if xs else None

# decorator
from functools import cache
@cache
def fib(n): return n if n < 2 else fib(n-1) + fib(n-2)

Control Flow

if x > 0: ...
elif x == 0: ...
else: ...

for i, v in enumerate(xs): ...
for k, v in d.items(): ...
while cond: ...

val = "yes" if flag else "no"   # ternary

match cmd:                       # 3.10+
    case "start": ...
    case (x, y): ...
    case _: ...

Classes & Dataclasses

class Dog:
    def __init__(self, name):
        self.name = name
    def bark(self):
        return f"{self.name}!"
    def __repr__(self):
        return f"Dog({self.name!r})"

class Puppy(Dog):
    def __init__(self, name):
        super().__init__(name)

from dataclasses import dataclass, field
@dataclass(frozen=True, slots=True)
class Point:
    x: float
    y: float
    tags: list[str] = field(default_factory=list)

Error Handling

try:
    risky()
except (ValueError, KeyError) as e:
    print(e)
    raise RuntimeError("failed") from e
else:
    print("ok")            # no exception
finally:
    cleanup()              # always runs

class MyError(Exception): ...

with open("f.txt") as f:   # context manager
    data = f.read()

Type Hints

Hint Meaning
list[int]list of ints
dict[str, int]str→int map
int | Noneoptional
type Vec = list[float]alias (3.12)

Stdlib One-liners

from collections import Counter, defaultdict, deque
Counter(xs).most_common(3)
dd = defaultdict(list)

from pathlib import Path
Path("f.txt").read_text()
Path("dir").glob("*.py")

import json
json.loads(s); json.dumps(obj, indent=2)

import itertools as it
it.chain(a, b); it.product(a, b)

from functools import reduce, partial

Async

import asyncio

async def fetch(u):
    await asyncio.sleep(1)
    return u

async def main():
    r = await asyncio.gather(fetch("a"), fetch("b"))
    async with asyncio.TaskGroup() as tg:   # 3.11+
        tg.create_task(fetch("c"))

asyncio.run(main())

Tooling Commands

python -m venv .venv
source .venv/bin/activate
pip install requests
pip freeze > requirements.txt

uv add requests          # fast modern manager
uv run python app.py

ruff check .             # lint
ruff format .            # format
mypy src/                # type check
pytest -q                # run tests
python -m http.server    # quick static server

Section navigation