Python Cheat Sheet
Quick reference for Python data structures, comprehensions, generators, standard library essentials, type hints, and common patterns.
Versions (November 2026)
| Version | Status | Headline features |
|---|---|---|
| 3.15 | Current (Oct 2026) | lazy import, frozendict and sentinel built-ins, */** unpacking in comprehensions, UTF-8 default encoding, profiling package |
| 3.14 | Bugfix | t-strings, deferred annotations, except A, B: without parens, free-threading officially supported, compression.zstd, concurrent.interpreters |
| 3.13 | Security only | New colour REPL, experimental free-threaded build and JIT, copy.replace(), warnings.deprecated |
| 3.12 | Security only | type statement, PEP 695 generics, f-string grammar relaxed, itertools.batched |
| 3.11 | Security only | TaskGroup, except*, tomllib, Self, big speed-ups |
| 3.10 | End-of-life (Oct 2026) | match, X | Y unions — upgrade |
Data Structures
Built-in Types
| Type | Literal | Mutable | Ordered | Duplicates |
|---|---|---|---|---|
list | [1, 2, 3] | Yes | Yes | Yes |
tuple | (1, 2, 3) | No | Yes | Yes |
set | {1, 2, 3} | Yes | No | No |
frozenset | frozenset({1, 2}) | No | No | No |
dict | {"a": 1} | Yes | Yes (3.7+) | Keys: No |
str | "hello" | No | Yes | Yes |
bytes | b"hello" | No | Yes | Yes |
bytearray | bytearray(b"hi") | Yes | Yes | Yes |
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, socase 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
| Command | Description |
|---|---|
pip install pkg | Install package |
pip install pkg==1.2.3 | Install specific version |
pip install -e . | Install in editable mode |
pip install --upgrade pkg | Upgrade package |
pip uninstall pkg | Uninstall package |
pip list | List installed packages |
pip show pkg | Package details |
pip check | Verify dependencies |
Poetry
| Command | Description |
|---|---|
poetry new project | Create new project |
poetry init | Initialize in existing directory |
poetry add requests | Add dependency |
poetry add --group dev pytest | Add dev dependency |
poetry remove pkg | Remove dependency |
poetry install | Install all dependencies |
poetry update | Update dependencies |
poetry lock | Regenerate lock file |
poetry run python script.py | Run within virtualenv |
eval $(poetry env activate) | Activate virtualenv (Poetry 2.x; poetry shell moved to the poetry-plugin-shell plugin) |
poetry build | Build package |
poetry publish | Publish 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):
| Command | Description |
|---|---|
uv init myapp | New project (--lib for a library, --package for an installable app) |
uv add requests | Add dependency (updates pyproject.toml, uv.lock, .venv) |
uv add --dev pytest ruff | Add dev dependency (dependency-groups.dev) |
uv remove requests | Remove dependency |
uv sync | Install exactly what the lock file says (--locked in CI fails if stale) |
uv lock --upgrade-package requests | Upgrade one locked package |
uv run pytest | Run a command in the project env (auto-syncs first) |
uv tree | Show dependency tree |
uv build / uv publish | Build sdist + wheel / upload to PyPI |
uv export --format requirements-txt | Export lock to requirements.txt |
Python versions, tools & scripts:
| Command | Description |
|---|---|
uv python install 3.15 | Download a managed Python |
uv python pin 3.14 | Write .python-version |
uvx ruff check . | Run a tool in a throwaway env (= uv tool run) |
uv tool install ruff | Install a CLI tool globally (pipx replacement) |
uv add --script tool.py httpx | Add inline (PEP 723) deps to a single script |
uv run tool.py | Run script with its inline deps |
pip-compatible interface (drop-in for existing requirements.txt workflows):
| Command | Description |
|---|---|
uv venv | Create virtual environment |
uv pip install requests | Install package (fast) |
uv pip compile requirements.in | Compile lock file |
uv pip sync requirements.txt | Sync environment |
uv run script.py | Run 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())
| Need | Use |
|---|---|
| Run many coroutines, fail fast | asyncio.TaskGroup (preferred over bare create_task) |
| Limit concurrency | asyncio.Semaphore(n) + async with sem: |
| Cancel a group early | tg.cancel() (3.15+) or raise inside the group |
| Producer/consumer | asyncio.Queue (.shutdown() in 3.13+) |
| CPU-bound work | ProcessPoolExecutor, 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
| Decision | Choice A | Choice B | Use A When | Use B When |
|---|---|---|---|---|
| Sequence | list | tuple | Mutable, variable size | Immutable, fixed structure |
| Mapping | dict | defaultdict | Explicit key init | Auto-initialize missing keys |
| Iteration | List comp | Generator expr | Need all results, small data | Lazy eval, large data |
| Data class | dataclass | namedtuple | Methods, mutability, defaults | Simple immutable records |
| Concurrency | threading | asyncio | I/O-bound, legacy code | I/O-bound, modern async |
| Concurrency | multiprocessing | threading | CPU-bound (bypass GIL) | I/O-bound (or CPU-bound on the free-threaded python3.14t build) |
| Pkg mgmt | pip + venv | poetry | Simple projects | Complex deps, publishing |
| Pkg mgmt | uv | pip + venv | New projects: locking, Python installs, speed | Environments where you can't add tools |
| Aliases | type X = ... | X: TypeAlias = ... | 3.12+ | Must support ≤ 3.11 |
| Branching | match | if/elif | Destructuring shapes (lists, dicts, classes) | Simple value comparisons |
| String fmt | f-string | .format() | Simple interpolation (3.6+) | Dynamic format strings |
Test Yourself
-
What method returns a value from a dict with a default if the key is missing?
d.get("key", default) -
How do you merge two dicts in Python 3.9+?
d1 | d2 -
What module provides
defaultdict,Counter, anddeque?collections -
How do you create a generator expression that sums squares lazily?
sum(x**2 for x in range(n)) -
What decorator memoizes function results with an LRU cache?
@lru_cache(maxsize=128)fromfunctools -
How do you remove duplicates from a list while preserving order?
list(dict.fromkeys(items)) -
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: -
How do you create an immutable dataclass?
@dataclass(frozen=True) -
What method on pathlib.Path recursively finds all Python files?
Path(".").rglob("*.py") -
What is the difference between
listandtuple?listis mutable and variable-size;tupleis immutable and fixed-structure.
Common Gotchas
- Mutable default arguments.
def f(items=[])shares the same list across all calls. Usedef f(items=None)withif 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. matchcaptures bare names.case RED:binds a new variableREDand always matches; usecase Color.RED:.- Fire-and-forget tasks get garbage collected. Keep a reference to
asyncio.create_task(...)results, or use aTaskGroup. - Default encoding. Before 3.15,
open()uses the locale encoding (often cp1252 on Windows); passencoding="utf-8"explicitly for portable code. returninfinallyswallows exceptions — 3.14 now emits aSyntaxWarningfor 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
iswith==.ischecks identity (same object),==checks equality (same value). Useisonly forNone,True,False. - Using
except Exceptionwithout 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.