Python
Updated: May 21, 2026Categories: Languages, Backend, Scientific
Printed from:
Complete Python Cheatsheet
Targets Python 3.12+ (modern syntax: PEP 695 type params, match, walrus, tomllib).
Table of Contents
- Setup & Toolchain
- Data Types
- Strings
- Lists, Tuples, Sets, Dicts
- Comprehensions
- Control Flow
- Functions
- Classes & Dataclasses
- Type Hints
- Modules & Packages
- Errors & Exceptions
- Iterators, Generators, Itertools
- Files & Paths
- Concurrency & Async
- Regex
- Date & Time
- JSON, CSV, YAML, TOML
- HTTP & Web
- Testing
- Standard Library Highlights
- Common Third-party Libraries
- Quick Reference
Setup & Toolchain
Bash
1234567891011121314151617181920212223242526# Install via uv (fastest modern installer/manager — recommended)
curl -LsSf https://astral.sh/uv/install.sh | sh
uv python install 3.12
uv venv .venv && source .venv/bin/activate
uv pip install requests
# Or via pyenv / official installer / brew
pyenv install 3.12.5
brew install python@3.12
# Project tooling
uv init my-app # creates pyproject.toml + .venv
uv add requests fastapi # adds dep + locks
uv sync # install from lockfile
uv run python main.py # auto-creates venv
# Classic flow (still works)
python -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
pip freeze > requirements.txt
# Formatters / linters / type checkers (modern picks)
uv add --dev ruff mypy pytest pre-commit
ruff format . && ruff check --fix .
mypy src/
Data Types
Python
1234567891011121314151617181920212223242526272829# Primitives
n: int = 42
f: float = 3.14
b: bool = True
s: str = "hello"
none = None
# Numeric
1_000_000 # underscores for readability
0xFF, 0o17, 0b1010, 1e3
2 ** 10 # 1024
17 // 5, 17 % 5 # floor div, mod
divmod(17, 5) # (3, 2)
round(1.55, 1) # banker's rounding
# Booleans (subclass of int)
True + 1 # 2
bool(""), bool([]), bool(0), bool(None) # all False
# Truthy / falsy
if not value: ... # None, 0, 0.0, "", [], {}, set(), False are falsy
# Type checks
isinstance(x, (int, float))
type(x) is int
# Conversions
int("42"), int("ff", 16), float("3.14"), str(42), bool(0)
Strings
Python
1234567891011121314151617181920212223242526272829303132s = "hello"
len(s)
s.upper() s.lower() s.title() s.capitalize() s.casefold()
s.strip() s.lstrip() s.rstrip()
s.startswith("he") s.endswith("o") "ll" in s
s.find("l") s.rfind("l") s.index("l") # index raises if missing
s.replace("l", "L") s.replace("l", "L", 1)
s.split(",") s.rsplit(",", 1) s.splitlines()
"-".join(["a", "b"])
s.ljust(10) s.rjust(10) s.zfill(5) s.center(11, "*")
s.encode("utf-8") # bytes
b"abc".decode("utf-8") # str
# f-strings (use these)
name, n = "Ada", 3
f"{name} × {n}"
f"{3.14159:.2f}" # "3.14"
f"{1_000_000:,}" # "1,000,000"
f"{42:>5}" # right-aligned, width 5
f"{42:#06x}" # "0x002a"
f"{x=}" # "x=42" (debug, 3.8+)
f"{datetime.now():%Y-%m-%d %H:%M}"
# Multiline / raw
"""multi
line"""
r"C:\path\to\file"
# Bytes vs str
b"bytes" # bytes literal
"text".encode() # → bytes
b"bytes".decode() # → str
Lists, Tuples, Sets, Dicts
Python
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748# List — ordered, mutable
xs = [1, 2, 3]
xs.append(4)
xs.extend([5, 6])
xs.insert(0, 0)
xs.pop() xs.pop(0)
xs.remove(2) # first occurrence
xs.index(3)
xs.count(1)
xs.sort() xs.sort(reverse=True) xs.sort(key=lambda x: -x)
sorted_xs = sorted(xs, key=str) # non-mutating
xs.reverse()
xs[1:4] xs[::-1] xs[::2] # slicing
xs[1:3] = [99, 100] # slice assignment
xs.copy() # shallow copy
xs + [7, 8]
xs * 3
# Tuple — ordered, immutable
t = (1, 2, 3)
t = 1, 2, 3
t = (1,) # one-element needs trailing comma
a, b, c = t # unpacking
a, *rest = [1, 2, 3]
# Set — unordered, unique
s = {1, 2, 3}
s.add(4); s.discard(99); s.remove(1)
s | {5} # union
s & {2, 3} # intersection
s - {2} # difference
s ^ {3, 5} # symmetric difference
s.issubset(other); s.issuperset(other); s.isdisjoint(other)
frozenset([1, 2]) # immutable
# Dict — ordered (insertion), mutable
d = {"a": 1, "b": 2}
d["a"]; d.get("c", 0)
d["c"] = 3
d.update({"d": 4}); d.update(e=5)
d.pop("a"); d.popitem()
"a" in d
d.keys(); d.values(); d.items()
{**d, **{"x": 99}} # merge (3.5+)
d | {"x": 99} # merge (3.9+)
{v: k for k, v in d.items()} # invert
dict.fromkeys(["a", "b"], 0)
Comprehensions
Python
1234567891011121314151617181920212223242526272829303132333435[x * 2 for x in range(5)] # list
[x for x in xs if x > 0] # filter
{x for x in xs} # set
{k: v for k, v in pairs} # dict
(��������ȁ������̤�������������������������������ɅѽȀ����䄤((��9��ѕ�)l���������ȁ�����Ʌ����̤���ȁ�����Ʌ����̥t)mm����ȁ�����ɽ�t���ȁɽ܁������ɥ�t((��݅���̀�̸ତ)m䁙�ȁ�������ф�������त��́��Ё9���t)���((���((���
���ɽ�����()�����ѡ��)���������(��������)�����������(��������)��͔�(��������((��Q�ɹ���)�������������͔����((��1����)��ȁ��������(�����ɥ�С�)��ȁ����������յ�Ʌє��̰��х���Ĥ�(�����ɥ�С����)��ȁ������������̰��̰���ɥ���Q�Ք�耀�������̸���(��������)ݡ���������(��������)��͔耀�����������������������������������������չ́��������������ѕ́ݥѡ��Ё�ɕ��(��������()�ɕ�������ѥ�Ք������((��5�э������͔��̸����)��э��������(������͔��������(���������ɥ�Р��ɥ�����(������͔��ఀ���(���������ɥ�С���́�Ё���(������͔��ఁ䤁���������(���������ɥ�Р�����������(������͔��ɽ���耉��������������聹�����(���������ɥ�С��������������(������͔�A���С��ఁ���耀������������������������́���ѕɸ(�����������(������͔�m����а��ɕ��t�(�����������(������͔�|�(���������ɥ�Р��ѡ�Ȉ�)���((���((���չ�ѥ���()�����ѡ��)�����ɕ�С�������Ȱ����ѥѱ����Ȁ�Ȉ���������(�������I���ɸ����ɕ�ѥ����Qɥ�����սѕ�������ɥ������(����ɕ��ɸ���!����ѥѱ��������((��A�ͥѥ����������ݽɐ�����ɝ̀�����݅ɝ̀����ͥѥ��������䀼����ݽɐ�����)���������}���䰀������}��}�ܰ���ɝ̰���}���䰀���݅ɝ̤耸��((�����ձ�̃�P���݅ɔ���х��������ձ��)����������mt�老ๅ������Ĥ�ɕ��ɸ������������j���<�͡�ɕ����ɽ�́�����)�����������9�����(�������mt�������́9������͔��((��1�����̀�͡��а����ɕ�ͥ�������)�������������聄����((��
����ɕ�)������չѕȠ��(��������(��������������(������������������쁸�����ɕ��ɸ��(����ɕ��ɸ����((�����Ʌѽ��)�ɽ���չ�ѽ��́�����Ё�Ʌ��)���������������(�����Ʌ�̡���(������������Ƞ��ɝ̰����ܤ�(���������ɥ�С����������홸�}}����}}�(��������ɕ��ɸ������ɝ̰����ܤ(����ɕ��ɸ������()������)��������������ɕ��ɸ������((��U͕�հ��ե�е�������Ʌѽ�̀���չ�ѥ���)�ɽ���չ�ѽ��́�����Ё����������}����������ѥ����ɕ�Ս�)�����)�����������ɕ��ɸ����������ȁ��͔���������Ĥ�����������Ȥ()���ѥ�����а���͔��ؤ����������������)ɕ�Ս�������������聄������lİ�Ȱ��t����)���((���((���
���͕̀���х����͕�()�����ѡ��)����́������(����������������������������������������������́����(����}}ͱ���}|���������}��������������������ѥ����聙��ѕȰ���ᕐ������((��������}}����}|�͕�����������Ȱ����聥�Ѐ�������9����(��������͕����������(��������͕���}�����((�����ɽ�����(������������͕�����������ɕ��ɸ�͕���}���((��������͕�ѕ�(������������͕�����聥�Ф����9����(���������������Ʌ�͔�Y��Օ�ɽȠ�����ѥٔ��(��������͕���}������((���������ɕ�С͕�����������(��������ɕ��ɸ���$����͕��������((��������͵�ѡ��(���������������̤��������ɕ��ɸ���̹}}����}|((�����хѥ���ѡ��(���������������}��չР���������ɕ��ɸ��|���|���((��������}}ɕ��}|�͕�����������ɕ��ɸ����������͕������������(��������}}��}|�͕�����ѡ�Ȥ�ɕ��ɸ��ͥ��х�����ѡ�Ȱ������������͕����������ѡ�ȹ����(��������}}��͡}|�͕����ɕ��ɸ���͠�͕��������(()����́����������(����������ɬ�͕�����������ɕ��ɸ��ݽ���(���������ɕ�С͕�����������(��������ɕ��ɸ�����Ƞ���ɕ�Р��������������(((���х����͕̃�P���Ѽ�}}����}|�}}ɕ��}|�}}��}|)�ɽ����х����͕́�����Ё��х����̰������()��х����̡ͱ����Q�Ք���ɽ镸�Q�Ք����}�����Q�Ք�)����́A�����(�����聙����(�����聙����(����х��聱���m���t���������ձ�}���ѽ������Ф()���A���С��İ���Ȥ)���((���((���Q����!����()�����ѡ��)�ɽ��������������Ё�䰁=�ѥ������
���������%ѕɅ�����%ѕɅѽȰ�M��Օ�����5������()�聥�Ѐ��)�聙���Ё��9�����9������������������̸����չ������х�)�聱���m���t��mt)�聑���m��Ȱ����t����)�������m��а���Ȱ������t��İ������ĸ��()��������聱���m���t�����
�������mm���t������t��9�����������耸��((��Aɽѽ���̀����Ս��Ʌ���������)�ɽ��������������ЁAɽѽ���)����́!��9����Aɽѽ�����(������������((�����ɥ���չ�ѥ��̀������͕̀�A@����A�ѡ���̸�Ȭ�)���������mQt���聱���mQt�����P���9����(����ɕ��ɸ���l�t�����́��͔�9���()����́Mх��mQt�(��������}}����}|�͕�������9����͕���}��聱���mQt��mt(����������͠�͕������P�����9����͕���}�̹��������((��1�ѕɅ�̀��Q������Ѐ��9����Q����)�ɽ��������������Ё1�ѕɅ���Q������а�9����Q����)5�����1�ѕɅ�l�Ȉ���܈���Ɉ�t)����́U͕ȡQ������Ф�(������聥��(������������)A���Ѐ�9����Q������A���Ј��l��������Ф����䈰���Хt�((��Q��������͕̀�A@���Ԥ)�����Y��ѽȀ��m�����t)���()Iո�����䀹����ȁ���ɥ��р��Ѽ����Յ��䁍�����ѡ���((���((���5��ձ�̀��A�������()�����ѡ��(��%������)�����Ё��Ѡ)�ɽ����Ѡ������Ё�������Ё�́�)�ɽ���������Ёͥ�����������������ɕ��ѥٔ((��
����ѥ�����������)�����̹���љ�ɴ����ݥ���(���������Ё�����}ѡ���((��Iո��̵͍ɥ�Ё�����)���}}����}|���}}����}|��(����������((��5��ձ�������)}}����}|��}}����}|��}}���}|((��A�����������Ѐ�ݥѠ����ɽ���йѽ���)��}����+�Rs�R�R�����ɽ���йѽ��+�Rs�R�R���Ɍ�+�R����RS�R�R����}����+�R��������Rs�R�R��}}����}|���+�R��������RS�R�R��������+�RS�R�R��ѕ��̼((�����ɽ���йѽ��������մ)m�ɽ����t)����������)ٕ�ͥ������ĸ��)�����������̀�l�ɕ�Օ�����ȉt)m�ե������ѕ�t)ɕ�եɕ̀�l���э������t)�ե������������э�������ե���)���((���((����ɽ�̀��ፕ�ѥ���()�����ѡ��)����(������}ѡ�����)�ፕ�Ѐ�Y��Օ�ɽȰ�-���ɽȤ��́��(�����ɥ�С��)�ፕ�Ёፕ�ѥ���(����Ʌ�͔����������������������������ɔ�Ʌ�͔����ɕ��)��͔�(�����ɥ�Р������ɽȈ�������� # only if try succeeded
finally:
cleanup()
# Custom exception
class HttpError(Exception):
def __init__(self, msg, status):
super().__init__(msg)
self.status = status
raise HttpError("not found", status=404)
raise HttpError("wrap") from original_error # cause
# Exception groups (3.11+)
try: ...
except* ValueError as eg: # handle a group
...
# Common exceptions
ValueError TypeError KeyError IndexError
FileNotFoundError PermissionError
RuntimeError StopIteration
AttributeError ImportError ModuleNotFoundError
ZeroDivisionError OverflowError
Iterators, Generators, Itertools
Python
123456789101112131415161718192021222324252627282930313233# Generators (lazy sequences)
def count_up_to(n):
i = 0
while i < n:
yield i
i += 1
# `yield from`
def chain(*its):
for it in its:
yield from it
# Iterator protocol
class Counter:
def __init__(self, n): self.n = n; self.i = 0
def __iter__(self): return self
def __next__(self):
if self.i >= self.n: raise StopIteration
self.i += 1; return self.i
# itertools — every Python project uses this
from itertools import (
chain, cycle, repeat, count,
accumulate, pairwise, batched, # batched added 3.12
combinations, permutations, product,
groupby, islice, takewhile, dropwhile, tee,
zip_longest, starmap, compress,
)
list(pairwise([1, 2, 3, 4])) # [(1,2),(2,3),(3,4)]
list(batched("abcdef", 2)) # [('a','b'),('c','d'),('e','f')]
list(accumulate([1, 2, 3, 4])) # [1, 3, 6, 10]
Files & Paths
Python
12345678910111213141516171819202122232425262728293031from pathlib import Path
p = Path("data") / "users.json"
p.exists(); p.is_file(); p.is_dir()
p.parent; p.name; p.stem; p.suffix
p.read_text(encoding="utf-8")
p.write_text("hi")
p.read_bytes() / p.write_bytes(b"")
p.with_suffix(".csv")
p.with_name("new.json")
p.resolve() p.expanduser() Path.cwd() Path.home()
list(p.glob("*.json")) list(p.rglob("**/*.py"))
p.mkdir(parents=True, exist_ok=True)
p.unlink(missing_ok=True)
p.rename("new.txt")
# Old-school open()
with open("file.txt", "r", encoding="utf-8") as f:
for line in f: print(line.rstrip())
# tempfile
import tempfile
with tempfile.NamedTemporaryFile(delete=False) as tmp:
tmp.write(b"data")
# os/shutil
import os, shutil
os.environ.get("HOME")
os.makedirs("a/b", exist_ok=True)
shutil.copy(src, dst); shutil.copytree(src, dst); shutil.rmtree(dst)
Concurrency & Async
Python
1234567891011121314151617181920212223242526272829303132# Threads (good for I/O, limited by GIL for CPU)
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, as_completed
with ThreadPoolExecutor(max_workers=8) as ex:
futures = [ex.submit(fetch, url) for url in urls]
for f in as_completed(futures):
print(f.result())
with ProcessPoolExecutor() as ex: # use for CPU-bound
results = list(ex.map(square, range(1000)))
# asyncio (built-in)
import asyncio
import httpx
async def fetch(url):
async with httpx.AsyncClient() as c:
r = await c.get(url)
return r.text
async def main():
results = await asyncio.gather(*(fetch(u) for u in urls))
async with asyncio.TaskGroup() as tg: # 3.11+
for u in urls:
tg.create_task(fetch(u))
asyncio.run(main())
# Useful asyncio primitives
asyncio.sleep, asyncio.wait_for(coro, timeout=5)
asyncio.Lock, asyncio.Semaphore, asyncio.Queue, asyncio.Event
Regex
Python
123456789101112131415161718import re
re.match(r"\d+", "123abc") # match at start
re.search(r"\d+", "abc123def") # anywhere
re.findall(r"\d+", "a1 b22 c333") # ["1","22","333"]
re.finditer(r"\d+", text) # iterator of Match
re.sub(r"\s+", " ", text)
re.split(r"[,;]\s*", "a, b;c")
# Compile + groups
pat = re.compile(r"(?P<year>\d{4})-(?P<month>\d{2})")
m = pat.search("2026-05")
m.group("year"), m.groups() # ("2026", ...)
# Flags
re.IGNORECASE re.MULTILINE re.DOTALL re.VERBOSE
re.search(r"foo", s, re.IGNORECASE | re.MULTILINE)
Date & Time
Python
1234567891011121314151617181920212223242526from datetime import date, time, datetime, timedelta, timezone
from zoneinfo import ZoneInfo
datetime.now() # local
datetime.now(timezone.utc)
datetime.now(ZoneInfo("Europe/Paris"))
d = date(2026, 5, 20)
d.isoformat() # "2026-05-20"
date.fromisoformat("2026-05-20")
date.today()
dt = datetime.fromisoformat("2026-05-20T10:00:00+00:00")
dt.strftime("%Y-%m-%d %H:%M:%S")
datetime.strptime("2026-05-20", "%Y-%m-%d")
now = datetime.now(timezone.utc)
yesterday = now - timedelta(days=1, hours=3)
(now - yesterday).total_seconds()
# time, timeit
import time
t0 = time.perf_counter(); work(); time.perf_counter() - t0
import timeit
timeit.timeit("'-'.join(str(n) for n in range(100))", number=10_000)
JSON, CSV, YAML, TOML
Python
1234567891011121314151617181920import json
json.dumps(obj, indent=2, default=str, ensure_ascii=False)
json.loads(text)
with open("data.json") as f: data = json.load(f)
with open("data.json", "w") as f: json.dump(obj, f, indent=2)
import csv
with open("data.csv", newline="") as f:
for row in csv.DictReader(f): ...
with open("out.csv", "w", newline="") as f:
w = csv.DictWriter(f, fieldnames=["id", "name"]); w.writeheader(); w.writerow({...})
# TOML — read built-in (3.11+); write via tomli-w
import tomllib
with open("pyproject.toml", "rb") as f: cfg = tomllib.load(f)
# YAML — pip install pyyaml
import yaml
data = yaml.safe_load(open("config.yaml"))
HTTP & Web
Python
12345678910111213141516171819202122232425262728293031# httpx (sync + async; modern requests replacement)
import httpx
r = httpx.get("https://api.example.com", params={"q": "x"}, timeout=10)
r.raise_for_status()
r.json()
with httpx.Client() as c:
c.post(url, json={"x": 1}, headers={"Authorization": "Bearer ..."})
# requests (still very common)
import requests
requests.get(url).json()
# Standard library (no deps)
from urllib.request import urlopen
from urllib.parse import urlencode, urlparse, parse_qs
urlopen("https://example.com").read()
# Web frameworks (pick one)
# FastAPI (async, type-driven):
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root(): return {"ok": True}
# Flask (simple, sync):
from flask import Flask
app = Flask(__name__)
@app.get("/")
def root(): return {"ok": True}
Testing
Python
123456789101112131415161718192021222324252627# pytest
# tests/test_x.py
import pytest
def add(a, b): return a + b
def test_add():
assert add(2, 3) == 5
@pytest.mark.parametrize("a,b,exp", [(1,2,3),(2,3,5)])
def test_add_params(a, b, exp):
assert add(a, b) == exp
def test_raises():
with pytest.raises(ValueError, match="bad"):
raise ValueError("bad input")
@pytest.fixture
def client():
c = make_client(); yield c; c.close()
# unittest (stdlib)
import unittest
class TestX(unittest.TestCase):
def test_x(self):
self.assertEqual(1 + 1, 2)
Standard Library Highlights
Python
12345678910111213141516171819202122232425262728293031323334353637383940import collections
collections.Counter("abracadabra") # {"a":5,"b":2,...}
collections.defaultdict(list)
collections.deque([1, 2, 3], maxlen=3)
collections.OrderedDict; collections.namedtuple
import functools
functools.cache functools.lru_cache(maxsize=128)
functools.partial(int, base=16)
functools.reduce(op, seq, initial)
functools.singledispatch # type-based dispatch
import itertools # see Iterators section
import operator
operator.itemgetter("id")
operator.attrgetter("name")
operator.methodcaller("upper")
import contextlib
@contextlib.contextmanager
def temp(): setup(); yield; teardown()
contextlib.suppress(FileNotFoundError)
contextlib.closing(resource)
import pathlib, os, shutil, sys
import logging
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
import argparse
p = argparse.ArgumentParser(); p.add_argument("--name"); args = p.parse_args()
import subprocess
subprocess.run(["ls", "-la"], capture_output=True, text=True, check=True)
import sqlite3
con = sqlite3.connect(":memory:"); cur = con.cursor()
cur.execute("CREATE TABLE t(x)"); cur.executemany("INSERT INTO t VALUES(?)", [(1,),(2,)])
Common Third-party Libraries
| Domain | Library |
|---|---|
| HTTP | httpx, requests, aiohttp |
| Data | pandas, polars, numpy, pyarrow |
| ML / AI | pytorch, transformers, scikit-learn, xgboost |
| Web framework | fastapi, flask, django, litestar |
| ORM | sqlalchemy, tortoise-orm, peewee, sqlmodel |
| Validation | pydantic, attrs, msgspec |
| CLI | typer, click, argparse |
| Async | asyncio, anyio, trio |
| Task queue | celery, rq, dramatiq, arq |
| Testing | pytest, hypothesis, pytest-asyncio |
| Lint / format | ruff, black, isort |
| Types | mypy, pyright |
| Packaging | uv, poetry, hatch, setuptools |
Quick Reference
Python
1234567891011121314151617181920212223242526272829303132333435363738394041# Collections
list / tuple / set / dict / frozenset
xs[1:5:2] xs[::-1] xs + ys xs * 3
"\n".join(xs) sorted(xs, key=...) reversed(xs)
d.get(k, default) d | other (3.9+) {**a, **b}
*rest, x = xs; a, *mid, z = xs
# Comprehensions
[f(x) for x in xs if pred(x)]
{k: v for k, v in pairs}
(x for x in xs) # generator (lazy)
# Functions
def f(x, y=1, *args, kw=2, **kwargs): ...
*args **kwargs / * (PEP 570)
# Modern syntax
match x:
case Pattern(): ...
case _: ...
x := walrus
[s := f(x), s + 1]
# Async
async def f(): await g()
asyncio.run(main())
async with ...; async for ...
# Types (3.12+)
def f[T](x: T) -> T: ...
type Vector = list[float]
# Files
Path("x").read_text() / write_text()
with open(p) as f: ...
# Tools
uv add ruff mypy pytest
ruff format . && ruff check --fix .
mypy src/ pytest -q
Tip: in 2025+, default toolchain is uv + ruff + mypy/pyright + pytest. Use
pathlib.Path,httpx, f-strings,match, type hints, and dataclasses — they replace half the older idioms.
Continue Learning
Discover more cheatsheets to boost your productivity