Cheatsheet

Python Syntax Cheatsheet

Every core Python construct on one page. From basics to modern features (walrus, structural pattern matching, type hints). Use it, then drill it with flashcards.

Python's syntax is deceptively simple. The core is small enough to fit on one page, but 'the core' now includes structural pattern matching (added in 3.10), the walrus operator (3.8), positional-only parameters (3.8), and type hints across the board. If you learned Python in 2016 you missed all of it.

This cheatsheet compresses every widely used syntactic construct into one page. Use it as a lookup, then convert the pieces you keep forgetting into a flashcard deck. Coding without checking syntax is where speed comes from.

Variables and types

Assignment: `x = 5`. Multiple: `a, b = 1, 2`. Walrus (assign inside expression): `if (n := len(data)) > 10: ...` — added in 3.8.

Type hints: `x: int = 5`, `def f(x: int) -> str: ...`, `from typing import Optional, Union` (or `int | None` in 3.10+).

Constants convention: `SCREAMING_SNAKE = 42` — not enforced, just a convention.

Control flow

`if/elif/else`, `while`, `for x in iterable`. `for..else` runs the else if loop completes without break.

Structural pattern matching (3.10+): `match value: case 1: ... case [x, y]: ... case {"key": v}: ... case _: ...`

Ternary: `x if cond else y`. Guard clauses over deep nesting.

Data structures

List `[1, 2, 3]`, tuple `(1, 2, 3)`, set `{1, 2, 3}`, dict `{"k": "v"}`. Frozen versions: `frozenset()`, no immutable dict in stdlib.

Comprehensions: `[x*2 for x in xs if x>0]`, `{k: v for k, v in pairs}`, `{x for x in xs}`. Generator: `(x*2 for x in xs)` — lazy, one pass.

Unpacking: `a, *rest = [1,2,3,4]`. Dict merge: `{**a, **b}` or 3.9+ `a | b`.

Functions

`def f(x, y=1, *args, **kwargs): ...`. Positional-only before `/`, keyword-only after `*`: `def f(a, b, /, c, *, d): ...`.

Lambdas: `lambda x: x*2` — one expression only, no statements.

Decorators: `@cache`, `@functools.lru_cache(maxsize=128)`, custom: `def deco(f): def wrapper(*a, **kw): ...; return wrapper`.

Classes

`class Foo:` with `__init__(self, x)` for construction. `@dataclass` from `dataclasses` auto-generates `__init__`, `__repr__`, `__eq__` from annotated fields.

Inheritance: `class Bar(Foo):`. Multiple inheritance uses MRO (`Foo.__mro__`).

Common dunders: `__str__`, `__repr__`, `__eq__`, `__hash__`, `__iter__`, `__len__`, `__enter__`/`__exit__` (context managers).

Async

`async def f(): await g()`. Run with `asyncio.run(main())`. Concurrent tasks: `asyncio.gather(f(), g())`.

Async context manager: `async with resource() as r:`. Async iteration: `async for x in stream():`.

Exceptions

`try: ... except ValueError as e: ... else: ... finally: ...`. Custom: `class MyError(Exception): pass`.

Exception groups (3.11+): `try: ... except* ValueError: ...` for handling multiple errors from concurrent tasks.

`raise ValueError('x') from source_exc` to chain exceptions.

Frequently asked questions

Is this cheatsheet up to date with Python 3.13?

Yes. Structural pattern matching, walrus operator, positional-only parameters, exception groups, and native `int | None` union syntax are all covered. Older syntax that still works is included where it is still common.

Where does f-string formatting fit?

`f"{name}: {value:.2f}"` — quoted with `f` prefix, expressions in braces, format spec after colon. In 3.12 you can also nest quotes: `f"{d['key']}"`.

Should I use `list.append()` or `+=`?

`append` is clearest for single elements. `extend` or `+=` for multiple. `+` creates a new list — avoid in hot loops.

What about the walrus operator — is it worth using?

Yes, in narrow cases: reading input in a loop (`while chunk := f.read(1024)`) and inside comprehensions (`[y for x in data if (y := transform(x)) is not None]`). Overusing it hurts readability.

Are type hints required?

No. Python is dynamically typed. Type hints are checked by tools like mypy or Pyright but ignored at runtime unless you use `typing.get_type_hints()` explicitly. They pay off in libraries and large codebases; they are optional in scripts.

Keep exploring

Made for exam season

Pass that exam.

Turn your notes into flashcards and quizzes in seconds. Study smarter — start free today.