On this page

Python Cheat Sheet

Quick reference for Python data structures, comprehensions, generators, standard library essentials, type hints, and common patterns.


Versions (November 2026)

VersionStatusHeadline features
3.15Current (Oct 2026)lazy import, frozendict and sentinel built-ins, */** unpacking in comprehensions, UTF-8 default encoding, profiling package
3.14Bugfixt-strings, deferred annotations, except A, B: without parens, free-threading officially supported, compression.zstd, concurrent.interpreters
3.13Security onlyNew colour REPL, experimental free-threaded build and JIT, copy.replace(), warnings.deprecated
3.12Security onlytype statement, PEP 695 generics, f-string grammar relaxed, itertools.batched
3.11Security onlyTaskGroup, except*, tomllib, Self, big speed-ups
3.10End-of-life (Oct 2026)match, X | Y unions — upgrade

Data Structures

Built-in Types

TypeLiteralMutableOrderedDuplicates
list[1, 2, 3]YesYesYes
tuple(1, 2, 3)NoYesYes
set{1, 2, 3}YesNoNo
frozensetfrozenset({1, 2})NoNoNo
dict{"a": 1}YesYes (3.7+)Keys: No
str"hello"NoYesYes
bytesb"hello"NoYesYes
bytearraybytearray(b"hi")YesYesYes

List Operations

nums = [3, 1, 4, 1, 5]
nums.append(9)              # Add to end
nums.extend([2, 6])         # Add multiple
nums.insert(0, 0)           # Insert at index
nums.pop()                  # Remove & return last
nums.pop(2)                 # Remove & return at index
nums.remove(1)              # Remove first occurrence
nums.sort()                 # Sort in place
nums.sort(reverse=True)     # Sort descending
sorted(nums)                # Return new sorted list
nums.reverse()              # Reverse in place
nums.index(4)               # First index of value
nums.count(1)               # Count occurrences

Dict Operations

d = {"a": 1, "b": 2}
d["c"] = 3                  # Set key
d.get("x", 0)               # Get with default
d.setdefault("x", [])       # Get or set default
d.update({"d": 4, "e": 5})  # Merge dict
d | {"f": 6}                # Merge (3.9+, returns new)
d |= {"f": 6}               # Merge in place (3.9+)
d.pop("a")                  # Remove & return value
d.keys()                    # View of keys
d.values()                  # View of values
d.items()                   # View of (key, value) pairs
del d["b"]                  # Delete key

Set Operations

a = {1, 2, 3}
b = {3, 4, 5}
a | b                       # Union: {1, 2, 3, 4, 5}
a & b                       # Intersection: {3}
a - b                       # Difference: {1, 2}
a ^ b                       # Symmetric difference: {1, 2, 4, 5}
a.issubset(b)               # Is a subset of b?
a.issuperset(b)             # Is a superset of b?

Comprehensions & Generators

# List comprehension
squares = [x**2 for x in range(10)]

# Filtered comprehension
evens = [x for x in range(20) if x % 2 == 0]

# Dict comprehension
word_len = {w: len(w) for w in ["hello", "world"]}

# Set comprehension
unique_lower = {s.lower() for s in ["Hi", "HI", "hi"]}

# Nested comprehension (flatten)
flat = [x for row in matrix for x in row]

# Generator expression (lazy, memory efficient)
total = sum(x**2 for x in range(1_000_000))

# Generator function
def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

# Unpacking in comprehensions (3.15+)
flat = [*row for row in matrix]          # same as the nested comprehension above
merged = {**d for d in dicts}            # later dicts win

String Operations

s = "Hello, World!"
s.upper()                   # "HELLO, WORLD!"
s.lower()                   # "hello, world!"
s.strip()                   # Remove leading/trailing whitespace
s.split(", ")               # ["Hello", "World!"]
", ".join(["a", "b", "c"])  # "a, b, c"
s.replace("World", "Py")   # "Hello, Py!"
s.startswith("Hello")       # True
s.endswith("!")             # True
s.find("World")             # 7 (index or -1)
s.count("l")                # 3
f"val={42:08d}"             # "val=00000042" (f-string format)
f"{3.14159:.2f}"            # "3.14" (2 decimal places)
f"{1234567:,}"              # "1,234,567" (thousands separator)
f"{0.25:.0%}"               # "25%"
f"{name!r:>10}"             # repr, right-aligned in 10 chars
f"{x=}"                     # "x=42" (self-documenting, 3.8+)
f"{'nested "quotes" ok'}"   # same-quote nesting allowed (3.12+)
s.removeprefix("Hello, ")   # "World!" (3.9+; unlike lstrip, removes the exact prefix)
s.removesuffix("!")         # "Hello, World"
s.partition(", ")           # ("Hello", ", ", "World!")

Template strings (t-strings, 3.14+)

from string.templatelib import Template, Interpolation

user = "Robert'); DROP TABLE students;--"
t = t"SELECT * FROM users WHERE name = {user}"   # a Template, NOT a str
type(t)                                           # <class 'string.templatelib.Template'>
t.strings                                         # ('SELECT * FROM users WHERE name = ', '')
t.values                                          # ("Robert'); DROP TABLE students;--",)
# A library (SQL, HTML, shell) walks the parts and escapes/parameterises each Interpolation.

Common Standard Library

itertools

from itertools import (
    chain, islice, groupby, product,
    combinations, permutations, accumulate, count, cycle, repeat
)

chain([1,2], [3,4])              # 1, 2, 3, 4
islice(range(100), 5, 10)        # 5, 6, 7, 8, 9
groupby(sorted(data), key=fn)    # Group consecutive equal elements
product("AB", "12")              # A1, A2, B1, B2
combinations([1,2,3], 2)         # (1,2), (1,3), (2,3)
permutations([1,2,3], 2)         # (1,2), (1,3), (2,1), ...
accumulate([1,2,3,4])            # 1, 3, 6, 10 (running sum)

from itertools import batched, pairwise
batched("ABCDEFG", 3)            # ('A','B','C'), ('D','E','F'), ('G',)  (3.12+)
pairwise([1,2,3,4])              # (1,2), (2,3), (3,4)  (3.10+)

collections

from collections import (
    defaultdict, Counter, deque, namedtuple, OrderedDict
)

# defaultdict - auto-initialize missing keys
dd = defaultdict(list)
dd["key"].append(1)

# Counter - count occurrences
c = Counter("abracadabra")       # Counter({'a': 5, 'b': 2, ...})
c.most_common(2)                 # [('a', 5), ('b', 2)]

# deque - double-ended queue, O(1) append/pop both ends
dq = deque([1, 2, 3], maxlen=5)
dq.appendleft(0)
dq.rotate(1)                    # [3, 0, 1, 2]

# namedtuple - lightweight immutable class
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x, p.y)

pathlib

from pathlib import Path

p = Path("/usr/local/bin")
p / "python3"                    # /usr/local/bin/python3
p.exists()                       # True/False
p.is_file()                      # True/False
p.is_dir()                       # True/False
p.name                           # "bin"
p.stem                           # filename without suffix
p.suffix                         # file extension
p.parent                         # /usr/local
p.glob("*.py")                   # Generator of matching files
p.rglob("*.py")                  # Recursive glob
Path.cwd()                       # Current working directory
Path.home()                      # Home directory

# Read/write
Path("file.txt").read_text()
Path("file.txt").write_text("content")
Path("dir").mkdir(parents=True, exist_ok=True)

functools

from functools import lru_cache, partial, reduce, wraps

# lru_cache - memoize function results
@lru_cache(maxsize=128)
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)

# partial - fix some arguments
from operator import mul
double = partial(mul, 2)         # double(5) -> 10

# reduce - fold iterable
reduce(lambda a, b: a + b, [1, 2, 3, 4])  # 10

# cache - unbounded memoisation (3.9+), same as lru_cache(maxsize=None)
from functools import cache, cached_property

Other everyday modules

import json, tomllib, datetime as dt, logging, subprocess

json.dumps(obj, indent=2, default=str)       # default= handles datetimes etc.
json.loads(text)
with open("pyproject.toml", "rb") as f:      # tomllib (3.11+) is read-only, needs binary mode
    cfg = tomllib.load(f)

dt.datetime.now(dt.UTC)                      # timezone-aware now (dt.UTC alias 3.11+)
dt.datetime.fromisoformat("2026-11-09T10:00:00+00:00")

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
log = logging.getLogger(__name__)

subprocess.run(["git", "status"], check=True, capture_output=True, text=True).stdout

Type Hints

Basic Type Hints

# Variables
name: str = "Alice"
age: int = 30
scores: list[int] = [90, 85, 92]
lookup: dict[str, int] = {"a": 1}

# Functions
def greet(name: str, excited: bool = False) -> str:
    return f"Hello, {name}{'!' if excited else '.'}"

# Optional (value or None)
def find(key: str) -> str | None:       # 3.10+ syntax
    ...

# Union types
def process(val: int | str) -> None:    # 3.10+ syntax
    ...

Advanced Type Hints

from typing import (
    TypeVar, Generic, Protocol, Callable,
    TypeAlias, Literal, TypeGuard, Final
)

# TypeVar for generics (pre-3.12 style; still valid, but prefer PEP 695 below)
T = TypeVar("T")
def first(items: list[T]) -> T:
    return items[0]

# Protocol (structural subtyping / duck typing)
class Drawable(Protocol):
    def draw(self) -> None: ...

# Callable
Handler = Callable[[str, int], bool]

# Literal
Mode = Literal["r", "w", "a"]

# TypeAlias (deprecated since 3.12 in favour of the `type` statement below)
Vector: TypeAlias = list[float]

# Final (constant)
MAX_SIZE: Final = 100

Modern Generics & Aliases (PEP 695, 3.12+)

from collections.abc import Callable, Iterable, Sequence
from typing import Protocol, Self, TypeIs, override

# Type parameters inline — no TypeVar boilerplate
def first[T](items: Sequence[T]) -> T:
    return items[0]

def biggest[T: (int, float)](a: T, b: T) -> T:   # constrained
    return max(a, b)

class Box[T]:                                    # generic class, no Generic[T] base
    def __init__(self, item: T) -> None:
        self.item = item

class SupportsLen(Protocol):
    def __len__(self) -> int: ...

def longest[T: SupportsLen](xs: Iterable[T]) -> T:   # bound
    return max(xs, key=len)

# `type` statement: lazily evaluated, can be recursive and generic
type Vector = list[float]
type Tree[T] = T | list[Tree[T]]
type Handler = Callable[[str, int], bool]

# Self (3.11+), @override (3.12+), TypeIs (3.13+, narrows both branches unlike TypeGuard)
class Node:
    def clone(self) -> Self: ...

class Child(Node):
    @override
    def clone(self) -> Self: ...

def is_str_list(val: list[object]) -> TypeIs[list[str]]:
    return all(isinstance(x, str) for x in val)

Annotations are lazy since 3.14

PEP 649/749: annotations are evaluated only when inspected, so forward references (def f(x: Later) -> Later) no longer need quotes or from __future__ import annotations. Read them with annotationlib.get_annotations().


Pattern Matching (match, 3.10+)

def handle(cmd):
    match cmd:
        case ["go", direction]:                       # sequence pattern, binds direction
            return f"going {direction}"
        case ["pick", "up", *items]:                  # star capture
            return f"picking {items}"
        case {"action": "move", "x": int(x), "y": int(y)}:   # mapping + class pattern
            return f"move to {x},{y}"
        case Point(x=0, y=0):                         # class pattern by attribute
            return "origin"
        case int() | float() as n if n < 0:           # OR pattern + capture + guard
            return "negative"
        case str(s):
            return f"string {s!r}"
        case _:                                       # wildcard (default)
            return "unknown"
  • A bare name (case direction:) captures, it doesn't compare. Compare against constants with dotted names (case Color.RED:) or literals.
  • Mapping patterns match if the listed keys exist; extra keys are ignored.
  • Dataclasses get __match_args__ automatically, so case Point(0, 0): works positionally.

Dataclasses

from dataclasses import dataclass, field

@dataclass
class User:
    name: str
    email: str
    age: int = 0
    tags: list[str] = field(default_factory=list)

    def greeting(self) -> str:
        return f"Hi, I'm {self.name}"

# Auto-generates __init__, __repr__, __eq__
u = User("Alice", "alice@example.com", 30)

# Frozen (immutable)
@dataclass(frozen=True)
class Point:
    x: float
    y: float

# Slots (less memory, faster attribute access, 3.10+)
@dataclass(slots=True)
class Config:
    host: str
    port: int

# Keyword-only fields (3.10+) and copy-with-changes (3.13+)
import copy
@dataclass(frozen=True, kw_only=True)
class Settings:
    debug: bool = False
    workers: int = 4

s2 = copy.replace(Settings(), workers=8)   # dataclasses.replace() on older versions

Virtual Environments & Package Management

venv (Built-in)

python -m venv .venv              # Create virtual environment
source .venv/bin/activate         # Activate (Linux/macOS)
.venv\Scripts\activate            # Activate (Windows)
deactivate                        # Deactivate
pip install requests              # Install package
pip install -r requirements.txt   # Install from file
pip freeze > requirements.txt     # Export installed packages

pip

CommandDescription
pip install pkgInstall package
pip install pkg==1.2.3Install specific version
pip install -e .Install in editable mode
pip install --upgrade pkgUpgrade package
pip uninstall pkgUninstall package
pip listList installed packages
pip show pkgPackage details
pip checkVerify dependencies

Poetry

CommandDescription
poetry new projectCreate new project
poetry initInitialize in existing directory
poetry add requestsAdd dependency
poetry add --group dev pytestAdd dev dependency
poetry remove pkgRemove dependency
poetry installInstall all dependencies
poetry updateUpdate dependencies
poetry lockRegenerate lock file
poetry run python script.pyRun within virtualenv
eval $(poetry env activate)Activate virtualenv (Poetry 2.x; poetry shell moved to the poetry-plugin-shell plugin)
poetry buildBuild package
poetry publishPublish to PyPI

uv (Fast Package Manager)

uv is the de-facto default for new projects: one Rust binary that replaces pip, venv, pip-tools, pipx and pyenv, with a cross-platform uv.lock.

Project workflow (uses pyproject.toml + uv.lock, manages .venv for you):

CommandDescription
uv init myappNew project (--lib for a library, --package for an installable app)
uv add requestsAdd dependency (updates pyproject.toml, uv.lock, .venv)
uv add --dev pytest ruffAdd dev dependency (dependency-groups.dev)
uv remove requestsRemove dependency
uv syncInstall exactly what the lock file says (--locked in CI fails if stale)
uv lock --upgrade-package requestsUpgrade one locked package
uv run pytestRun a command in the project env (auto-syncs first)
uv treeShow dependency tree
uv build / uv publishBuild sdist + wheel / upload to PyPI
uv export --format requirements-txtExport lock to requirements.txt

Python versions, tools & scripts:

CommandDescription
uv python install 3.15Download a managed Python
uv python pin 3.14Write .python-version
uvx ruff check .Run a tool in a throwaway env (= uv tool run)
uv tool install ruffInstall a CLI tool globally (pipx replacement)
uv add --script tool.py httpxAdd inline (PEP 723) deps to a single script
uv run tool.pyRun script with its inline deps

pip-compatible interface (drop-in for existing requirements.txt workflows):

CommandDescription
uv venvCreate virtual environment
uv pip install requestsInstall package (fast)
uv pip compile requirements.inCompile lock file
uv pip sync requirements.txtSync environment
uv run script.pyRun script with deps
# /// script
# requires-python = ">=3.12"
# dependencies = ["httpx"]
# ///
import httpx            # `uv run tool.py` creates an env with httpx automatically

Common Patterns

Context Managers

# Using built-in
with open("file.txt", "r") as f:
    content = f.read()

# Custom context manager (class)
class Timer:
    def __enter__(self):
        self.start = time.perf_counter()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.elapsed = time.perf_counter() - self.start
        return False  # Do not suppress exceptions

with Timer() as t:
    do_work()
print(f"Took {t.elapsed:.3f}s")

# Context manager with contextlib
from contextlib import contextmanager

@contextmanager
def temp_dir():
    path = tempfile.mkdtemp()
    try:
        yield path
    finally:
        shutil.rmtree(path)

Decorators

import functools

# Basic decorator
def log_calls(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__}")
        result = func(*args, **kwargs)
        print(f"{func.__name__} returned {result}")
        return result
    return wrapper

@log_calls
def add(a, b):
    return a + b

# Decorator with arguments
def retry(max_attempts=3, delay=1.0):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for attempt in range(max_attempts):
                try:
                    return func(*args, **kwargs)
                except Exception:
                    if attempt == max_attempts - 1:
                        raise
                    time.sleep(delay)
        return wrapper
    return decorator

@retry(max_attempts=5, delay=2.0)
def fetch_data(url):
    ...

Exception Handling

# Basic try/except
try:
    result = risky_operation()
except ValueError as e:
    print(f"Bad value: {e}")
except (TypeError, KeyError):
    print("Type or key error")
except Exception as e:
    print(f"Unexpected: {e}")
    raise  # Re-raise
else:
    print("No exception occurred")
finally:
    cleanup()

# Custom exception
class AppError(Exception):
    def __init__(self, message: str, code: int):
        super().__init__(message)
        self.code = code

# Chain the cause (keeps the original traceback)
try:
    int("x")
except ValueError as e:
    raise AppError("bad config", 400) from e

# Multiple types without parentheses (3.14+, only when there's no `as`)
try:
    connect()
except TimeoutError, ConnectionRefusedError:
    retry()

# Add context to an exception (3.11+)
try:
    load(path)
except OSError as e:
    e.add_note(f"while loading {path}")
    raise

# ExceptionGroup / except* (3.11+) — what TaskGroup raises
try:
    raise ExceptionGroup("batch", [ValueError("a"), KeyError("b")])
except* ValueError as eg:
    print("value errors:", eg.exceptions)
except* KeyError:
    print("key errors")

asyncio

import asyncio

async def fetch(i: int) -> int:
    await asyncio.sleep(0.1)
    return i * 2

async def main() -> None:
    # Structured concurrency (3.11+): all tasks finish or all are cancelled
    async with asyncio.TaskGroup() as tg:
        tasks = [tg.create_task(fetch(i)) for i in range(5)]
    print([t.result() for t in tasks])            # [0, 2, 4, 6, 8]

    # Timeouts (3.11+)
    try:
        async with asyncio.timeout(1.0):
            await fetch(1)
    except TimeoutError:
        print("too slow")

    # Run blocking code without blocking the loop
    data = await asyncio.to_thread(Path("big.txt").read_text)

    # gather still works; return_exceptions=True collects errors instead of raising
    results = await asyncio.gather(fetch(1), fetch(2), return_exceptions=True)

asyncio.run(main())
NeedUse
Run many coroutines, fail fastasyncio.TaskGroup (preferred over bare create_task)
Limit concurrencyasyncio.Semaphore(n) + async with sem:
Cancel a group earlytg.cancel() (3.15+) or raise inside the group
Producer/consumerasyncio.Queue (.shutdown() in 3.13+)
CPU-bound workProcessPoolExecutor, InterpreterPoolExecutor (3.14+), or the free-threaded build

Useful One-Liners

# Flatten nested list
flat = [x for sub in nested for x in sub]

# Transpose matrix
transposed = list(zip(*matrix))

# Remove duplicates preserving order
unique = list(dict.fromkeys(items))

# Chunk a list
chunks = [lst[i:i+n] for i in range(0, len(lst), n)]

# Merge dicts
merged = {**d1, **d2}                # 3.5+
merged = d1 | d2                     # 3.9+

# Ternary expression
result = "yes" if condition else "no"

# Walrus operator (3.8+)
if (n := len(data)) > 10:
    print(f"Too long: {n}")

# Unpack with star
first, *middle, last = [1, 2, 3, 4, 5]

# Enumerate with start index
for i, val in enumerate(items, start=1):
    print(f"{i}. {val}")

# Iterate two lists, error if lengths differ (3.10+)
for a, b in zip(xs, ys, strict=True):
    ...

# Lazy import — module loads on first use (3.15+, module scope only)
lazy import json

When to Use X vs Y

DecisionChoice AChoice BUse A WhenUse B When
SequencelisttupleMutable, variable sizeImmutable, fixed structure
MappingdictdefaultdictExplicit key initAuto-initialize missing keys
IterationList compGenerator exprNeed all results, small dataLazy eval, large data
Data classdataclassnamedtupleMethods, mutability, defaultsSimple immutable records
ConcurrencythreadingasyncioI/O-bound, legacy codeI/O-bound, modern async
ConcurrencymultiprocessingthreadingCPU-bound (bypass GIL)I/O-bound (or CPU-bound on the free-threaded python3.14t build)
Pkg mgmtpip + venvpoetrySimple projectsComplex deps, publishing
Pkg mgmtuvpip + venvNew projects: locking, Python installs, speedEnvironments where you can't add tools
Aliasestype X = ...X: TypeAlias = ...3.12+Must support ≤ 3.11
Branchingmatchif/elifDestructuring shapes (lists, dicts, classes)Simple value comparisons
String fmtf-string.format()Simple interpolation (3.6+)Dynamic format strings

Test Yourself
  1. What method returns a value from a dict with a default if the key is missing? d.get("key", default)

  2. How do you merge two dicts in Python 3.9+? d1 | d2

  3. What module provides defaultdict, Counter, and deque? collections

  4. How do you create a generator expression that sums squares lazily? sum(x**2 for x in range(n))

  5. What decorator memoizes function results with an LRU cache? @lru_cache(maxsize=128) from functools

  6. How do you remove duplicates from a list while preserving order? list(dict.fromkeys(items))

  7. What is the walrus operator and when was it introduced? := (Python 3.8+), it assigns a value inside an expression: if (n := len(data)) > 10:

  8. How do you create an immutable dataclass? @dataclass(frozen=True)

  9. What method on pathlib.Path recursively finds all Python files? Path(".").rglob("*.py")

  10. What is the difference between list and tuple? list is mutable and variable-size; tuple is immutable and fixed-structure.

Common Gotchas

  • Mutable default arguments. def f(items=[]) shares the same list across all calls. Use def f(items=None) with if items is None: items = [] (items or [] also replaces a caller's empty list with a new one).
  • Late-binding closures. [lambda: i for i in range(3)] all return 2. Bind early: lambda i=i: i.
  • match captures bare names. case RED: binds a new variable RED and always matches; use case Color.RED:.
  • Fire-and-forget tasks get garbage collected. Keep a reference to asyncio.create_task(...) results, or use a TaskGroup.
  • Default encoding. Before 3.15, open() uses the locale encoding (often cp1252 on Windows); pass encoding="utf-8" explicitly for portable code.
  • return in finally swallows exceptions — 3.14 now emits a SyntaxWarning for it.
  • Modifying a list while iterating over it. This skips elements or raises errors. Iterate over a copy or use a comprehension to filter.
  • Confusing is with ==. is checks identity (same object), == checks equality (same value). Use is only for None, True, False.
  • Using except Exception without re-raising. Silently swallowing exceptions hides bugs. Always log or re-raise.

One-Liner Summary

Python is the Swiss Army knife of programming -- expressive syntax, batteries-included stdlib, and a massive ecosystem make it the go-to language for scripting, data science, web backends, and automation.