Skip to main content

Learning Resources

Cheatsheet

A complete Python cheatsheet — every major concept in one page: syntax, strings, lists/dicts, OOP, exceptions, generators, decorators, concurrency, files, pip/venv, coding templates, and interview traps. Ideal for last-minute revision.

Quick Reference

Python Programming Cheatsheet

Every major Python concept on one page — program structure, types, operators, control flow, strings, lists and dicts, functions, OOP, dunders, exceptions, modules, files, comprehensions, stdlib highlights, typing, asyncio, testing, coding templates, version notes, and interview traps. Built for revision before interviews and for looking things up while you code.

21 sections 36 tables 81 code snippets

Program Structure, Output & Input

Minimal program

print("Hello, Python!")

def main() -> None:
    name = "Ravi"
    print(f"Hello, {name}!")

if __name__ == "__main__":
    main()

Run, modules, venv

python hello.py              # run a script
python -m pip install requests
python -m venv .venv         # create virtual env
# Windows: .venv\Scripts\activate
# Unix:    source .venv/bin/activate
python -c "print(2+2)"       # one-liner
python -i script.py          # run then drop into REPL
python -m http.server 8000

print / input

print("a", "b", sep="-", end="!\n")
print(f"{42:05d} | {3.14159:.2f}")
name = input("Name: ")
age = int(input("Age: "))
# Multiple values from one line
a, b = map(int, input().split())

Command-line arguments

import sys
# python greeter.py Ravi 21
if len(sys.argv) < 3:
    sys.exit("usage: greeter.py NAME AGE")
name, age = sys.argv[1], int(sys.argv[2])
print(f"{name} is {age}")

argparse essentials

import argparse
p = argparse.ArgumentParser(description="Demo")
p.add_argument("path")
p.add_argument("-n", "--count", type=int, default=1)
p.add_argument("-v", "--verbose", action="store_true")
args = p.parse_args()

Shebang & encoding

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Module docstring goes here."""

Special variables

NameMeaning
__name__"__main__" when run as script; else module name
__file__Path to the current module file (if any)
__doc__Module / function / class docstring
sys.argvCommand-line args; [0] is script path
sys.pathModule search path list

f-string / format mini-language

SpecMeaningExampleResult
{x}Defaultf"{42}"42
{x:5d} / {x:<5d}Width 5, right / leftf"{42:5d}" 42
{x:05d}Zero-paddedf"{42:05d}"00042
{x:,}Thousands separatorf"{1000000:,}"1,000,000
{x:.2f}2 decimal placesf"{3.14159:.2f}"3.14
{x:.2%}Percentf"{0.25:.2%}"25.00%
{x:#x} / {x:b}Hex / binaryf"{255:#x}"0xff
{x!r} / {x!s}repr / strf"{x!r}"'hi'
{x=}Debug (3.8+)f"{n=}"n=42

Rules: Indentation defines blocks (usually 4 spaces). No semicolons needed. # starts a comment. The entry guard if __name__ == "__main__": keeps importable modules from running side effects.

Data Types, Variables & Casting

Built-in scalar types

TypeExamplesTruthy?Notes
int42, 1_000, 0x2A, 0b1010nonzeroArbitrary precision
float3.14, 1e-3, float("inf")nonzeroIEEE-754 double
complex3+4jnonzero.real, .imag
boolTrue, FalseTrue onlySubclass of int
str"hi", 'hi', """..."""nonemptyImmutable Unicode
bytesb"hi", bytes(3)nonemptyImmutable 0–255
NoneTypeNoneneverSingleton null

Collections at a glance

TypeMutableOrdered*Typical use
listyesyesSequence of items
tuplenoyesFixed record / hashable
dictyesyes (3.7+)Key → value map
setyesnoUnique membership
frozensetnonoHashable set

Literals & casting

n = 42
x = 3.14
s = "42"
b = True
nothing = None

int("42"); float("3.14"); str(42)
bool(0)          # False
bool([])         # False
list("abc")      # ['a', 'b', 'c']
tuple([1, 2])
set([1, 1, 2])   # {1, 2}
dict(a=1, b=2)

Identity, equality, truthiness

a = [1]; b = [1]
a == b           # True  (value)
a is b           # False (identity)
a is not None    # preferred null check

# Falsy: None, False, 0, 0.0, "", [], {}, set()
if items:        # nonempty?
    process(items)

Multiple assignment & unpacking

x, y = 1, 2
x, y = y, x                 # swap
a, *mid, z = [1, 2, 3, 4]   # mid = [2, 3]
first, second = "ab"

Constants & typing style

MAX_SIZE = 100              # convention: UPPER
PI = 3.14159
from typing import Final
RATE: Final = 0.05

Truthy / falsy quick map

Valuebool(...)
None, FalseFalse
0, 0.0, 0jFalse
"", b""False
[], (), {}, set()False
Most other objectsTrue

Tip: Names are references. b = a aliases the same object for mutables. Use copy.copy / copy.deepcopy when you need a real duplicate.

Operators & Expressions

Operator groups

KindOperatorsNotes
Arithmetic+ - * / // % **/ always float; // floor div
Comparison== != < > <= >=Chainable: 1 < x < 10
Identityis, is notSame object (use for None)
Membershipin, not inContainers / substrings
Booleanand or notShort-circuit; return operands
Bitwise& | ^ ~ << >>Integers
Assignment= += -= *= /= //= %= **=Also := walrus (3.8+)
Unpack / pack*, **Args / kwargs / merge

Division & power quirks

5 / 2      # 2.5
5 // 2     # 2
-5 // 2    # -3  (floor toward -inf)
5 % 2      # 1
2 ** 10    # 1024
pow(2, 10, 1000)  # 24  (modular)

Boolean & walrus

x or "default"      # first truthy
x and y             # y if x else x
(n := len(items)) > 0 and print(n)

# Ternary
status = "ok" if code == 200 else "err"

Augmented assignment

OpEquivalent ideaNotes
+=x = x + yLists: extends in place
*=x = x * yLists: repeats in place
/=x = x / yAlways float result
//=x = x // yFloor division
%=x = x % yModulo
**=x = x ** yPower
&= |= ^=Bitwise in placeInts / sets (|= union)

Precedence (high → low)

LevelOperators
Highest() calls, slicing, attribute
**
+x -x ~x
* / // %
+ -
<< >>
& then ^ then |
Comparisons, is, in
not then and then or
Lowestlambda / assignment expressions

Gotcha: -5 // 2 is -3, not -2. Use math.trunc / int() toward zero when that is what you want.

Control Flow

if / elif / else

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
else:
    grade = "C"

match / case (3.10+)

match command.split():
    case ["quit"]:
        return
    case ["load", filename]:
        load(filename)
    case ["move", x, y] if int(x) >= 0:
        move(int(x), int(y))
    case _:
        print("unknown")

for / while / else

for i in range(5):
    if i == 3:
        break
    if i % 2 == 0:
        continue
    print(i)
else:
    print("no break")   # runs if loop finished

n = 3
while n > 0:
    n -= 1

range & enumerate

range(5)          # 0..4
range(2, 10, 2)   # 2,4,6,8
range(5, 0, -1)   # 5..1

for i, item in enumerate(items, start=1):
    print(i, item)

for a, b in zip(xs, ys):
    print(a, b)

match patterns (3.10+)

PatternMatches
case 1:Equality to 1
case "go":String literal
case [x, y]:Sequence of length 2
case {"k": v}:Mapping with key k
case Point(x=0, y=y):Class __match_args__ / keywords
case _:Wildcard (default)
case x if x > 0:Capture + guard

Loop helpers

PatternCodeUse
Index + valueenumerate(seq)Need position
Parallel iterzip(a, b)Pair sequences
Sorted keysfor k in sorted(d)Stable key order
Reversereversed(seq)View, not copy
Early exitbreak / returnStop searching
SkipcontinueNext iteration
No-op bodypassPlaceholder

Loop else: runs only when the loop did not break. Handy for search-not-found patterns.

Strings & Text

Create & escape

s = "hello"
t = 'world'
m = """multi
line"""
raw = r"C:\new\path"     # backslashes kept
f"x={1+1}"              # f-string
b"bytes"                # bytes literal

Common methods

s.upper(); s.lower(); s.title()
s.strip(); s.lstrip("0"); s.rstrip()
s.startswith("he"); s.endswith("lo")
s.find("ll"); s.index("ll")   # -1 vs error
s.replace("l", "L", 1)
s.split(","); " ".join(["a", "b"])
s.isalpha(); s.isdigit(); s.isalnum()

Slicing & indexing

s = "Python"
s[0]; s[-1]          # 'P' 'n'
s[1:4]               # 'yth'
s[::-1]              # reverse
s[::2]               # every 2nd
# strings are immutable: s[0] = 'x'  # TypeError

Formatting styles

name, n = "Ravi", 42
f"{name} -> {n:04d}"
"{0} -> {1:04d}".format(name, n)
"%s -> %04d" % (name, n)         # older
template = "{name}"
template.format_map({"name": name})

Escape sequences

EscapeMeaning
\\Backslash
\n / \t / \rNewline / tab / carriage return
\' / \"Quote characters
\uXXXXUnicode BMP code point
\UXXXXXXXXFull Unicode code point
\xHHByte / Latin-1 hex
\N{name}Unicode by name

Useful string operations

NeedApproach
Split liness.splitlines()
Partition onces.partition("=") → (before, sep, after)
Pads.center(20), s.zfill(5)
Translate charss.translate(str.maketrans("ae", "AE"))
Casefold comparea.casefold() == b.casefold()
Removeprefix/suffix (3.9+)s.removeprefix("http://")
Encode / decodes.encode("utf-8") / b.decode()

Prefer f-strings for readability. Use !r when debugging (f"{obj!r}"). For user-facing templates with untrusted input, avoid str.format on attacker-controlled format strings.

Lists, Tuples & Sequences

List essentials

xs = [1, 2, 3]
xs.append(4)
xs.extend([5, 6])
xs.insert(0, 0)
xs.pop()            # last
xs.pop(0)           # by index
xs.remove(2)        # by value (first)
xs.clear()
ys = xs.copy()      # shallow

List algorithms

xs = [3, 1, 2]
xs.sort()                    # in place
sorted(xs, reverse=True)     # new list
xs.sort(key=str.lower)
xs.reverse()
xs.count(1); xs.index(2)
# Slice assignment
xs[1:3] = [9, 9]

Tuple & packing

t = (1, 2, 3)
one = (1,)              # trailing comma!
a, b, c = t
# Named fields (3.7+ dataclasses preferred for records)
from collections import namedtuple
Point = namedtuple("Point", "x y")
p = Point(3, 4)

Sequence operations

len(xs); min(xs); max(xs); sum(xs)
2 in xs
xs + [4, 5]             # concat (new)
xs * 3                  # repeat
all(xs); any(xs)
list(reversed(xs))

Common list methods

MethodEffectReturns
append(x)Add one item at endNone
extend(it)Add all from iterableNone
insert(i, x)Insert at indexNone
pop([i])Remove & return itemitem
remove(x)Remove first equal valueNone
sort(...)In-place sortNone
reverse()In-place reverseNone
copy()Shallow copynew list

list vs tuple

listtuple
Mutableyesno
Hashablenoyes (if items are)
Literal[1, 2](1, 2)
Use whenGrowing / changingFixed record, dict key
Methodsmany mutators.count, .index only

Slicing cheat sheet

SliceMeaning
a[i]Element at i (neg from end)
a[i:j]i inclusive … j exclusive
a[i:j:k]Step k
a[:]Shallow copy
a[::-1]Reversed copy
a[i:] / a[:j]From i / up to j
del a[i:j]Delete slice

Dictionaries & Sets

dict basics

d = {"a": 1, "b": 2}
d["c"] = 3
d.get("z", 0)           # default
d.setdefault("x", [])   # get or insert
del d["a"]
d.pop("b", None)
d.keys(); d.values(); d.items()
"a" in d                # keys only

Merge & unpack

a = {"x": 1}; b = {"y": 2}
{**a, **b}              # merge (right wins)
a | b                   # 3.9+ union
a |= b                  # in-place
dict.fromkeys(["a", "b"], 0)
# Comprehension
{k: v * 2 for k, v in b.items()}

set basics

s = {1, 2, 3}
s.add(4); s.discard(9)  # no error
s.remove(1)             # KeyError if missing
s | t; s & t; s - t; s ^ t
s <= t                  # subset
frozenset(s)            # immutable / hashable

collections helpers

from collections import Counter, defaultdict, deque
Counter("abracadabra")
dd = defaultdict(list)
dd["a"].append(1)
q = deque([1, 2], maxlen=10)
q.appendleft(0); q.pop()

Set algebra

Op / methodMeaning
s | t / unionAll unique elements
s & t / intersectionCommon elements
s - t / differenceIn s but not t
s ^ t / symmetric_differenceIn either, not both
s <= t / issubsets ⊆ t
s >= t / issupersets ⊇ t

dict / set methods

MethodEffect
d.update(other)Merge keys from other
d.popitem()Remove last inserted (3.7+)
d.clear()Empty the mapping
s.update(it)Add many to set
s.intersection_update(t)Keep only common
s.isdisjoint(t)No common elements

Keys must be hashable (immutable): str, int, tuple of hashables, frozenset. Lists and dicts cannot be keys.

Functions, Args & Scope

Definition & returns

def add(a: int, b: int = 0) -> int:
    """Return a + b."""
    return a + b

def stats(xs):
    return min(xs), max(xs), sum(xs) / len(xs)

lo, hi, avg = stats([1, 2, 3])

*args / **kwargs

def f(a, b, /, c, d=0, *, e, f=1, **kw):
    # a,b positional-only; e keyword-only
    return a, b, c, d, e, f, kw

f(1, 2, 3, e=4, extra=5)
# Unpack call
vals = (1, 2); f(*vals, 3, e=4)

lambda & higher-order

square = lambda x: x * x
sorted(words, key=lambda s: len(s))
list(map(str.upper, ["a", "b"]))
list(filter(lambda n: n % 2 == 0, range(10)))

closures & nonlocal

def make_counter():
    n = 0
    def inc():
        nonlocal n
        n += 1
        return n
    return inc

c = make_counter(); c(); c()  # 1, 2

Decorators

from functools import wraps

def logged(fn):
    @wraps(fn)
    def wrapper(*args, **kwargs):
        print(fn.__name__, args)
        return fn(*args, **kwargs)
    return wrapper

@logged
def greet(name):
    return f"hi {name}"

Scope LEGB

LetterWhereExample
LLocal function bodyx = 1 inside def
EEnclosing (closure)nonlocal x
GGlobal moduleglobal x
BBuiltinslen, print

Parameter kinds

SyntaxMeaning
aPositional or keyword
b=0Optional with default
/Prior args positional-only (3.8+)
*Following args keyword-only
*argsExtra positionals → tuple
**kwargsExtra keywords → dict

Default trap: never use a mutable default (def f(xs=[])). Use None and assign inside: xs = [] if xs is None else xs.

Classes & Object-Oriented Python

Class basics

class Person:
    species = "Homo sapiens"      # class attr

    def __init__(self, name: str, age: int):
        self.name = name
        self.age = age

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

p = Person("Ravi", 21)
print(p.greet(), Person.species)

Inheritance & super

class Animal:
    def speak(self):
        return "..."

class Dog(Animal):
    def speak(self):
        return "woof"

class GuardDog(Dog):
    def speak(self):
        return super().speak() + "!"

isinstance(Dog(), Animal)   # True
issubclass(Dog, Animal)     # True

@property / classmethod / staticmethod

class Circle:
    def __init__(self, r):
        self._r = r

    @property
    def area(self):
        return 3.14159 * self._r ** 2

    @classmethod
    def unit(cls):
        return cls(1)

    @staticmethod
    def tip():
        return "use dataclasses for data"

dataclass

from dataclasses import dataclass, field

@dataclass(order=True, slots=True)
class Item:
    name: str
    price: float = 0.0
    tags: list[str] = field(default_factory=list)

Item("pen", 1.5)

Access levels (convention)

NameMeaning
namePublic
_nameInternal (soft private)
__nameName-mangled to _Cls__name
__name__Language dunder — do not invent casually

OOP vocabulary

ConceptPython
Constructor__init__
Instance attrself.x = ...
Class attrAssigned in class body
Private-by-convention_name
Name mangling__name → _Class__name
Abstract baseabc.ABC + @abstractmethod
Multiple inheritanceclass C(A, B): (MRO)
Mixin patternSmall helper base classes

Everything is public by convention. A leading _ means “internal”. Prefer composition and dataclasses for plain data holders.

Special (Dunder) Methods

Repr, equality, hash

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __repr__(self):
        return f"Point({self.x!r}, {self.y!r})"

    def __eq__(self, other):
        return isinstance(other, Point) and (self.x, self.y) == (other.x, other.y)

    def __hash__(self):
        return hash((self.x, self.y))

Containers & callables

class Bag:
    def __init__(self):
        self._data = []

    def __len__(self):
        return len(self._data)

    def __getitem__(self, i):
        return self._data[i]

    def __iter__(self):
        return iter(self._data)

    def __contains__(self, x):
        return x in self._data

    def __call__(self, x):
        self._data.append(x)

Context manager

class Timer:
    def __enter__(self):
        import time
        self.t0 = time.perf_counter()
        return self

    def __exit__(self, exc_type, exc, tb):
        import time
        self.elapsed = time.perf_counter() - self.t0
        return False  # do not swallow

with Timer() as t:
    pass

Operator overloading

class Vec:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __add__(self, other):
        return Vec(self.x + other.x, self.y + other.y)

    def __mul__(self, k):
        return Vec(self.x * k, self.y * k)

    def __rmul__(self, k):
        return self.__mul__(k)

Common dunders

MethodTriggered by
__str__ / __repr__str(x) / repr(x) / printing
__len__len(x)
__bool__bool(x), if x:
__iter__ / __next__for, next()
__enter__ / __exit__with
__add__ / __iadd__+ / +=
__lt__ … __ge__Comparisons (functools.total_ordering)
__getattr__Missing attribute lookup

Exceptions & Context Managers

try / except / else / finally

try:
    n = int(text)
except ValueError as e:
    print("bad int", e)
except (TypeError, OSError):
    raise
else:
    print("ok", n)       # no exception
finally:
    print("always")

raise & custom

class OutOfRange(ValueError):
    pass

def set_age(age: int) -> None:
    if age < 0:
        raise OutOfRange(f"age={age}")
    if age > 150:
        raise ValueError("too old") from None

with / ExitStack

with open("a.txt") as f:
    data = f.read()

from contextlib import suppress, ExitStack
with suppress(FileNotFoundError):
    open("missing.txt").close()

with ExitStack() as stack:
    files = [stack.enter_context(open(p)) for p in paths]

EAFP vs LBYL

# EAFP — preferred Pythonic style
try:
    value = mapping[key]
except KeyError:
    value = default

# LBYL
if key in mapping:
    value = mapping[key]
else:
    value = default

Built-in exception tree (selected)

ExceptionTypical cause
SyntaxErrorInvalid source
NameErrorUndefined name
TypeErrorWrong type / arity
ValueErrorRight type, bad value
IndexErrorSequence index OOB
KeyErrorMissing mapping key
AttributeErrorMissing attribute
ZeroDivisionError/ // % by zero
FileNotFoundErrorMissing path
StopIterationIterator exhausted
RuntimeErrorGeneric runtime failure
AssertionErrorassert failed

Catch specific exceptions. Bare except: or except Exception: too early hides bugs. Use raise ... from e to chain causes.

Modules, Packages & Imports

Import forms

import math
import math as m
from math import sqrt, pi
from math import *          # avoid in libs
from package.sub import util

# Relatives inside a package
from . import sibling
from ..core import helper

Package layout

mypkg/
  __init__.py          # makes a package
  util.py
  sub/
    __init__.py
    helpers.py
# Namespace packages (3.3+) may omit __init__.py
# pyproject.toml / setup.cfg for installable projects

__name__ & sys.path

import sys
print(__name__)          # "__main__" or module name
sys.path.insert(0, "lib")
# Reload during REPL experiments
import importlib, math
importlib.reload(math)

Resource access

from importlib import resources
# Python 3.9+
text = resources.files("mypkg").joinpath("data.txt").read_text(encoding="utf-8")

Import rules

RuleWhy
Prefer absolute importsClearer, refactor-friendly
Avoid from x import *Pollutes namespace, hides origins
One package idea per dirKeeps APIs focused
Side-effect-light importsImporting should be cheap/safe
Use if __name__ == "__main__"Scripts stay importable

Files, pathlib & JSON

open patterns

with open("data.txt", "r", encoding="utf-8") as f:
    text = f.read()
    # f.readline(); f.readlines()
with open("out.txt", "w", encoding="utf-8") as f:
    f.write("hello\n")
with open("log.txt", "a", encoding="utf-8") as f:
    f.write("line\n")
# Binary
with open("img.bin", "rb") as f:
    blob = f.read()

pathlib

from pathlib import Path
p = Path("data") / "file.txt"
p.exists(); p.is_file(); p.suffix
p.read_text(encoding="utf-8")
p.write_text("hi", encoding="utf-8")
Path.cwd(); Path.home()
for child in Path(".").glob("**/*.py"):
    print(child)

JSON / CSV

import json, csv
json.dumps({"a": 1})
json.loads('{"a": 1}')
with open("d.json", "w", encoding="utf-8") as f:
    json.dump(obj, f, indent=2)

with open("t.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        print(row["name"])

temp & shutil

import tempfile, shutil
from pathlib import Path
with tempfile.TemporaryDirectory() as d:
    Path(d, "x.txt").write_text("ok", encoding="utf-8")
shutil.copy("a.txt", "b.txt")
shutil.move("b.txt", "c.txt")
shutil.rmtree("old_dir", ignore_errors=True)

pathlib highlights

APIPurpose
Path("a") / "b"Join parts
.name / .stem / .suffixFilename pieces
.resolve()Absolute + normalize
.exists() / .is_dir()Filesystem checks
.glob("**/*.py")Pattern walk
.read_text() / .write_text()Quick text I/O
.mkdir(parents=True, exist_ok=True)Create dirs

open modes

ModeMeaning
rRead text (default)
wWrite text (truncate)
xCreate new, fail if exists
aAppend
bBinary (combine: rb)
+Update (r+, w+)
tText (default)

Always set encoding="utf-8" for text on Windows. Prefer pathlib.Path over string concatenation for paths.

Comprehensions, Generators & Iterators

List / set / dict comps

squares = [x * x for x in range(10) if x % 2 == 0]
unique = {c.lower() for c in "AbBa"}
index = {c: i for i, c in enumerate("abc")}
# Nested
pairs = [(i, j) for i in range(3) for j in range(2)]

Generator expressions & yield

gen = (x * x for x in range(1_000_000))
sum(gen)

def countdown(n):
    while n > 0:
        yield n
        n -= 1

for x in countdown(3):
    print(x)

yield from & send

def flatten(nested):
    for xs in nested:
        yield from xs

def echo():
    while True:
        x = yield
        print("got", x)

g = echo(); next(g); g.send(10)

Iterator protocol

it = iter([10, 20, 30])
next(it)                 # 10
next(it, None)           # default if exhausted

class Count:
    def __init__(self, n): self.n, self.i = n, 0
    def __iter__(self): return self
    def __next__(self):
        if self.i >= self.n: raise StopIteration
        self.i += 1
        return self.i

When to use which

FormCreatesUse when
[...]listNeed random access / reuse
{...} setsetUniqueness
{k: v}dictMapping build
(...)generatorLazy / large / one-pass
yieldgenerator fnStateful streaming

Generators are single-pass. Exhausted generators yield nothing further. Materialize with list(gen) if you need reuse.

Key Standard Library

itertools / functools

import itertools as it
import functools as ft

list(it.islice(it.count(10), 3))     # 10,11,12
list(it.chain([1], [2, 3]))
list(it.combinations("ABC", 2))
ft.reduce(lambda a, b: a + b, [1, 2, 3], 0)
@ft.lru_cache(maxsize=128)
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)

datetime / math / random

from datetime import datetime, timedelta, timezone
now = datetime.now(timezone.utc)
now + timedelta(days=1)

import math, random, statistics
math.sqrt(2); math.gcd(12, 18)
random.choice([1, 2, 3]); random.random()
statistics.mean([1, 2, 3])

re / pathlib extras

import re
re.findall(r"\d+", "a12 b3")
re.sub(r"\s+", " ", "a   b")
m = re.match(r"(?P<y>\d{4})-(?P<m>\d{2})", "2026-10")
m.group("y") if m else None

os / sys / subprocess

import os, sys, subprocess
os.environ.get("HOME") or os.environ.get("USERPROFILE")
sys.version_info
subprocess.run(["python", "-c", "print(1)"], check=True)

itertools cheats

ToolUse
count(start)Infinite counter
cycle(xs)Repeat sequence forever
repeat(x, n)Same value n times
chain(a, b)Flatten one level
islice(it, n)Take first n
groupby(sorted_xs, key)Runs of equal keys
product(a, b)Cartesian product
permutations / combinationsCombinatorics

Module map

NeedModule
HTTP clienturllib.request / third-party requests
CLI argsargparse
Logginglogging
Testingunittest, pytest (ext)
Data classes helpersdataclasses, enum
Concurrencythreading, multiprocessing, asyncio
Serializationjson, pickle, struct
Compressiongzip, zipfile, tarfile
Hashinghashlib, hmac
Typing extrastyping, collections.abc

Type Hints

Core annotations

def greet(name: str, times: int = 1) -> str:
    return (f"hi {name}! " * times).strip()

nums: list[int] = [1, 2, 3]
pair: tuple[str, int] = ("a", 1)
book: dict[str, float] = {"pi": 3.14}
maybe: str | None = None          # 3.10+

typing toolkit

from typing import Callable, Iterable, TypeVar, Protocol, Literal, TypedDict

T = TypeVar("T")

def first(xs: Iterable[T]) -> T | None:
    for x in xs:
        return x
    return None

Handler = Callable[[str], int]

class User(TypedDict):
    id: int
    name: str

Protocol & generics

from typing import Protocol

class Closable(Protocol):
    def close(self) -> None: ...

def shutdown(resource: Closable) -> None:
    resource.close()

runtime checks

from typing import get_type_hints, reveal_type  # reveal_type: checkers only
import typing

hints = get_type_hints(greet)
assert typing.get_origin(list[int]) is list
assert typing.get_args(list[int]) == (int,)

Common hint forms

HintMeaning
list[int]List of ints (3.9+ builtin generics)
dict[K, V]Mapping
X | YUnion (3.10+); else Optional / Union
Literal["a", "b"]Exact values
Final[int]Should not be reassigned
ClassVar[int]Class variable, not instance
Self (3.11+)Return same class type
TypeGuardNarrowing helper for checkers

Hints are not enforced at runtime by default. Use mypy, pyright, or ty for checking. from __future__ import annotations postpones evaluation (often helpful).

Asyncio Essentials

async / await

import asyncio

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

async def main():
    a, b = await asyncio.gather(fetch(1), fetch(2))
    print(a, b)

asyncio.run(main())

tasks & timeout

async def work():
    async with asyncio.timeout(1.0):   # 3.11+
        await asyncio.sleep(0.1)
    task = asyncio.create_task(fetch(3))
    return await task

asyncio building blocks

APIRole
asyncio.run(main())Entry point
await coroSchedule and wait
create_task(coro)Concurrent task
gather(...)Wait for many
wait_for(coro, t)Timeout wrapper
Lock / Event / QueueSync primitives
to_thread(fn, ...)Offload blocking work (3.9+)

sync vs async

SyncAsync
def / returnasync def / return or await
time.sleepawait asyncio.sleep
threads for blocking I/Oevent loop + non-blocking I/O
concurrent.futuresasyncio.to_thread (3.9+) for blocking calls

Do not call blocking I/O inside async def without offloading — it stalls the event loop. Prefer async libraries (aiohttp, etc.) or asyncio.to_thread.

Testing & Debugging Snippets

unittest

import unittest

class TestAdd(unittest.TestCase):
    def test_add(self):
        self.assertEqual(1 + 1, 2)

    def test_raises(self):
        with self.assertRaises(ZeroDivisionError):
            _ = 1 / 0

if __name__ == "__main__":
    unittest.main()

pytest style

import pytest

def test_add():
    assert 1 + 1 == 2

@pytest.mark.parametrize("a,b,out", [(1, 2, 3), (0, 0, 0)])
def test_sum(a, b, out):
    assert a + b == out

def test_error():
    with pytest.raises(ValueError):
        int("x")

debug helpers

# breakpoint() opens pdb (3.7+)
x = 10
# breakpoint()

import traceback
try:
    1 / 0
except Exception:
    traceback.print_exc()

print(f"{x=}")   # debug f-string

assert & doctest

def clamp(n, lo, hi):
    """
    >>> clamp(5, 0, 10)
    5
    >>> clamp(-1, 0, 10)
    0
    """
    assert lo <= hi
    return max(lo, min(hi, n))

if __name__ == "__main__":
    import doctest
    doctest.testmod()

Assertions cheat sheet

unittestpytest
assertEqual(a, b)assert a == b
assertTrue(x)assert x
assertIn(a, b)assert a in b
assertRaises(E)pytest.raises(E)
assertAlmostEqualassert a == pytest.approx(b)

Coding Templates

CLI script skeleton

#!/usr/bin/env python3
from __future__ import annotations
import argparse
from pathlib import Path

def parse_args() -> argparse.Namespace:
    p = argparse.ArgumentParser()
    p.add_argument("path", type=Path)
    return p.parse_args()

def main() -> None:
    args = parse_args()
    text = args.path.read_text(encoding="utf-8")
    print(len(text))

if __name__ == "__main__":
    main()

Freq map / Counter

from collections import Counter
freq = Counter(word.lower() for word in text.split())
print(freq.most_common(5))

Two-pointer / sliding window

def max_sum_window(xs: list[int], k: int) -> int:
    window = sum(xs[:k])
    best = window
    for i in range(k, len(xs)):
        window += xs[i] - xs[i - k]
        best = max(best, window)
    return best

BFS / DFS graphs

from collections import deque

def bfs(graph, start):
    seen = {start}
    q = deque([start])
    while q:
        u = q.popleft()
        for v in graph[u]:
            if v not in seen:
                seen.add(v)
                q.append(v)
    return seen

def dfs(graph, start, seen=None):
    seen = seen or set()
    seen.add(start)
    for v in graph[start]:
        if v not in seen:
            dfs(graph, v, seen)
    return seen

Binary search

import bisect
xs = [1, 3, 5, 7]
bisect.bisect_left(xs, 5)   # 2
bisect.bisect_right(xs, 5)  # 3

def lower_bound(a, target):
    lo, hi = 0, len(a)
    while lo < hi:
        mid = (lo + hi) // 2
        if a[mid] < target:
            lo = mid + 1
        else:
            hi = mid
    return lo

Safe dict grouping

from collections import defaultdict
groups: dict[str, list[int]] = defaultdict(list)
for name, score in rows:
    groups[name].append(score)

Interview building blocks

Problem shapeTool
Frequency / anagramsCounter
Top-Kheapq.nlargest / Counter.most_common
Graph short path (unweighted)BFS + deque
Intervalssort by start, merge
Prefix sumsrunning total array
Monotonic stacknext greater element
Memoized recursionfunctools.lru_cache / cache

Version Highlights

Modern language features

VersionHighlights
3.8Walrus :=, f"{x=}", positional-only /
3.9list[int] builtins, dict |, str.removeprefix
3.10match/case, X | Y unions, better errors
3.11Exception groups, tomllib, faster CPython, Self
3.12Type alias type, f-string formalization, more perf
3.13Free-threaded preview, improved REPL, JIT experimental

Check your version

import sys
print(sys.version)
print(sys.version_info >= (3, 10))

Compat shims

from __future__ import annotations
try:
    from typing import Self  # 3.11+
except ImportError:
    from typing_extensions import Self

Gotchas & Interview Traps

TrapWhat happensRemember
Mutable default argShared across callsUse None + create inside
late binding in closuresAll lambdas see final loop valueDefault-arg bind: lambda i=i: i
is for ints / stringsMay be interned by chanceUse == for values; is for None
== vs is on listsValue vs identitya == b vs a is b
[+=[]] multiply[[]]*3 aliases same list[[] for _ in range(3)]
0.1 + 0.2 == 0.3Falsemath.isclose / Decimal
5 / 2 vs 5 // 22.5 vs 2Know float vs floor div
-5 // 2-3 (floor)Not truncating toward zero
Modifying list while iteratingSkipped items / errorsIterate a copy or build new
dict key order assumptions (old)Pre-3.7 unordered3.7+ insertion-ordered
Catching bare ExceptionHides bugsCatch specific types
except: without typeCatches KeyboardInterrupt tooNever bare except
daemonic thread + joinProcess may exit earlyJoin or mark carefully
asyncio + blocking callEvent loop freezesto_thread / async libs
* import in librariesNamespace clashesExplicit imports
Checking empty with lenVerbosePrefer if not xs:
sort vs sortedIn-place vs new listsort returns None
Chained comparisons surpriseFalse == False in [False] is TrueParenthesize when unsure
+= on tuples via list refTypeError or unexpectedTuples immutable; lists inside still mutate
hash randomizationSet/dict order varies across runsDon't rely on hash order
str vs repr in debugAmbiguous printsUse f"{x=}" / !r
Relative import outside packageImportErrorRun as module: python -m pkg.mod
Opening files without encodingLocale-dependent on WindowsAlways encoding="utf-8"

Classic mutable alias demo

rows = [[0] * 3] * 3
rows[0][0] = 1
print(rows)   # [[1, 0, 0], [1, 0, 0], [1, 0, 0]]

rows = [[0] * 3 for _ in range(3)]
rows[0][0] = 1
print(rows)   # [[1, 0, 0], [0, 0, 0], [0, 0, 0]]

Late-binding closure fix

funcs = [lambda: i for i in range(3)]
print([f() for f in funcs])          # [2, 2, 2]

funcs = [lambda i=i: i for i in range(3)]
print([f() for f in funcs])          # [0, 1, 2]

How to use this page: skim the jump chips, drill the tables, then type every snippet once in a REPL or IDE. Pair it with Interview Q&A for spoken answers and Real-life Examples for intuition.