BitSize Python · Recipes
Python Recipes.
The everyday Python patterns, run right in your browser.
String Literals — Four Kinds, One Mission
Single, double, raw, and triple-quoted strings each exist for a reason. Know when to use each.
f-String Basics — Interpolate Anything in One Shot
f'{variable}' injects a value. f'{expression}' evaluates any expression. f'{obj.method()}' calls methods inline.
f-String Format Specs — Control Exactly How Values Look
f'{value:.2f}' rounds floats. f'{n:,}' adds commas. f'{s:<10}' pads left. f'{n:08b}' converts to binary.
Text Alignment — Line Up Columns and Print Tidy Reports
Pad, align and wrap text so your terminal output reads like a neat receipt instead of a jumble.
str.split() and rsplit() — Break Text Apart
split() divides on whitespace or a delimiter. rsplit() starts from the right. maxsplit limits how many cuts.
str.join() — Assemble Strings the Right Way
sep.join(iterable) is O(n). Concatenation with += in a loop is O(n²). Always use join when building from parts.
strip, replace, count — The Daily Cleaning Trio
strip() removes edge characters. replace() substitutes text. count() finds occurrences. Three methods, endless utility.
startswith / endswith — Test Prefixes and Suffixes
endswith(('.jpg','.png')) checks multiple extensions in one call. No 'or' chains needed.
String Search — in, find(), index(), and When to Use Each
'x' in s is yes/no. find() gives position or -1. index() raises ValueError. Choose based on whether missing is an error.
Integer Operations — //, %, **, divmod()
// is floor division. % is remainder. ** is power. divmod() gives both at once. Together they solve a huge range of problems.
Float Gotchas — Why 0.1 + 0.2 ≠ 0.3 and How to Fix It
Floats are approximations. Never use == to compare them. round() for display. math.isclose() for comparison.
Boolean Truthiness — Every Object is True or False
Empty containers, zero, None, and False are falsy. Everything else is truthy. This rule applies everywhere in Python.
Boolean Short-Circuit — or-as-Default, and-as-Guard
'x or default' returns default only when x is falsy. 'cond and value' evaluates value only when cond is truthy. Neither returns True/False — they return operands.
Ternary Expression — if/else in One Line
value = x if condition else y. Works inside comprehensions, f-strings, and return statements.
The Walrus Operator := — Assign and Test in One Go
Compute a value, keep it, and test it in the same breath: tighter loops and no repeated work.
match / case — Branch on the Shape of Your Data
Replace tangled if/elif chains: match a value against literals, list shapes and dict shapes in one tidy block.
List Basics — append, extend, insert, remove, pop, index
append adds one item, extend adds many, insert places at a position, remove deletes by value, pop removes and returns.
List Slicing — Extract, Reverse, Step, and Copy
lst[2:5] extracts, lst[::-1] reverses, lst[::2] takes every other, lst[:] copies — all without a loop.
extend vs append — The Most Common Early Mistake
append([4, 5]) adds the list as ONE nested item; extend([4, 5]) adds each item. Same look, very different result.
References & Copies — Why Changing One List Changed Two
b = a doesn't copy anything: it gives the same list a second name. Learn when you need a real copy.
sorted() with key= — Sort Anything by Anything
sorted(items, key=func) sorts by whatever func returns. Tuple keys sort by several fields; negate a number to flip just that field.
enumerate() — Never Write range(len()) Again
enumerate(items) hands you (index, value) pairs; enumerate(items, start=1) counts from 1. Reach for it whenever you need a position.
zip() — Pair Iterables and Transpose Matrices
zip(a, b) pairs elements. dict(zip(k, v)) builds a dict. zip(*matrix) transposes. zip stops at the shortest.
Tuple Unpacking — Swap, Destructure, and Spread
a, b = b, a swaps without a temp. first, *rest = lst captures the rest. _ means 'I don't need this'.
any() + all() + next() — Search Without Building Lists
any() stops at first True. all() stops at first False. next(gen, default) finds first match. None build a list.
set() — Deduplication and O(1) Membership Testing
set() drops duplicates in one call, and "x in some_set" stays fast however big the set gets.
Set Operations — &, |, -, ^ — Think in Groups
& is intersection (in both), | is union (in either), - is difference (left only), ^ is symmetric difference (in exactly one).
dict.get() — Safe Access and the Counter Pattern
d[key] crashes on a missing key; d.get(key, default) never does. The same call powers the counting idiom.
dict Views — .items(), .keys(), .values() Are Live Windows
.items() gives (key, value) pairs, .values() feeds sums and averages, .keys() answers membership — and all three stay in sync with the dict.
namedtuple, NamedTuple & Enum — Lightweight Records
Stop writing row[2] and 'shipped' strings: give tuple fields names and fixed choices a proper type.
Counter & defaultdict — Count and Group in One Line
Stop writing if key not in d. Counter tallies, defaultdict(list) groups, and both live in collections.
Nested Dicts & Merging — Combine Settings Safely
Merge dicts with |, fill gaps with setdefault, and read deep keys without a single KeyError.
Stacks & Queues — list for LIFO, deque for FIFO
Undo buttons are stacks, print jobs are queues. Python gives you both in two lines.
List Comprehension — Replace for-append with One Line
[expr for x in items] transforms, [x for x in items if cond] filters, and one comprehension can do both.
Dict Comprehension — Build Lookup Tables in One Expression
{k: v for k, v in pairs} builds a dict, {v: k for k, v in d.items()} inverts one, and an if at the end filters it.
Conditional & Nested Comprehensions — Filter, Transform, Pair
An if at the end filters. An if/else at the front transforms. Two fors make every pair.
Flattening — Collapse Nested Lists into One
[x for row in rows for x in row] flattens one level; itertools.chain.from_iterable does the same lazily; zip(*rows) transposes.
Multiple Return Values — Tuple Unpacking from Functions
return a, b, c packs as a tuple. lo, hi = func() unpacks it. The caller decides how many values to use.
Default Arguments — The Mutable Default Trap
def f(lst=[]) shares ONE list across all calls. Always use None and create the mutable inside the function.
*args and **kwargs — Collect and Forward Anything
*args collects extra positional args as a tuple. **kwargs collects keyword args as a dict. Together they power every wrapper.
Keyword-Only Arguments — Force Callers to Name Parameters
def f(a, b, *, c, d) — parameters after * must be named. Prevents dangerous argument-order bugs with boolean flags.
Scope & LEGB — Where Python Looks Up a Name
Local, Enclosing, Global, Built-in: know the search order and a whole class of confusing bugs disappears.
lambda, map & filter — And When a Comprehension Is Better
A lambda is a tiny unnamed function. It shines as a sort key; for map and filter, a comprehension often reads better.
Functions as Values — Pass Them, Return Them, Remember State
In Python a function is just an object: store it, pass it, return it — and let it remember things.
functools Essentials — lru_cache, partial and reduce
Remember slow results with one decorator, pre-fill arguments with partial, and fold a list into one value.
try / except / else / finally — The Full Four-Part Pattern
try attempts. except handles failure. else runs ONLY on success. finally ALWAYS runs. Most devs skip else.
Catching Multiple Exceptions — Tuples and Re-raising
except (A, B) catches either. 'raise' re-raises the current exception. 'raise X from Y' chains exceptions.
Raising Your Own Exceptions — Fail Loudly, Fail Clearly
raise stops bad data at the door. A custom Exception subclass tells callers exactly what went wrong.
isinstance() — Correct Type Checking in Python
type(x) == int breaks with subclasses. isinstance(x, int) handles them correctly. Pass a tuple to check multiple types.
Assertions & Tiny Tests — Prove Your Code Works
Guard assumptions with assert, then build a ten-line test runner that prints PASS and FAIL for you.
Text-Cleaning Pipeline — From Messy Text to Word Stats
Lowercase, strip punctuation, split into words, count them. The four steps behind every word cloud.
Characters & Encodings — ord, chr, translate and Bytes
Every character is a number underneath. Shift it, swap it, encode it — and build a Caesar cipher on the way.
Number Bases & Bitwise Operators — Think in Binary
Read binary and hex, flip bits with & | ^ << >>, and pack yes/no permissions into a single number.
Parsing Structured Text — Turn Log Lines and Reports into Records
Logs, key=value strings and fixed-width reports: split them into fields and get dicts you can actually use.
Regex Search & Groups — Pull Dates, Codes and Emails Out of Text
re.search finds the first match, findall grabs them all, and groups pick out exactly the parts you want.
Regex sub, split & fullmatch — Clean, Cut and Validate Text
Rewrite text with re.sub, cut on messy separators with re.split, and check input strictly with fullmatch.
Text Files with `with` — Write, Read, Append Safely
open() inside a with block: the file is always closed, even if something goes wrong.
pathlib — Treat File Paths as Objects, Not Strings
Split names, join folders, read and write whole files, and list a folder — without a single string hack.
CSV & JSON — Save and Load Real Data Files
Spreadsheets and settings in, summaries out: the two file formats you will meet every week.
Nested JSON Data — Dig In, Stay Safe, Flatten It Out
API responses are dicts inside lists inside dicts: reach any value, survive missing keys, and flatten the lot.
Wrangling Records — Filter, Sort, Group and Summarise Like a Mini-pandas
A list of dicts is a table: query it, rank it and total it with plain Python before you ever reach for pandas.
Dates & Times — Deadlines, Durations and Formats with datetime
Add 30 days, count the days between two dates, and turn "2024-02-28 23:30" into something you can do maths on.
Numbers Toolkit — statistics, math, Decimal and Fraction
Averages in one call, boxes you need rounded up, and money that adds up to the exact cent.
Your First Class — Bundle Data and Behaviour Together
A class is a blueprint: write it once, then stamp out as many objects as you need.
Properties & Class Attributes — Smart Attributes, Shared State
Computed values that read like attributes, setters that refuse bad data, and counters every object shares.
Dunder Methods — Make Your Objects Feel Built-in
Teach your classes to print nicely, compare by value, sort, and answer len().
Inheritance & super() — Reuse a Class, Change What Differs
Child classes inherit everything, override only what changes, and call super() for the rest.
Dataclasses — Classes Without the Boilerplate
List the fields, add @dataclass, and get __init__, a readable repr and == for free.
Abstract Base Classes & Duck Typing — Contracts for Your Classes
Force subclasses to implement the methods that matter, or skip the hierarchy and just rely on what an object can do.
Custom Iterators — Make Your Own Objects Work in a for Loop
Teach a class __iter__ and __next__ and it plugs into for, list(), sum() and every other loop tool.
Context Managers — Setup and Cleanup That Always Runs
Write your own `with` blocks: open something, use it, and guarantee it is put back — even when errors fly.
Generator Functions — Produce Values Only When Asked
Swap return for yield and your function hands out values one at a time — no giant list in memory.
Generator Pipelines — Process a Log One Line at a Time
Chain small generators like pipes: read, clean, filter, parse — and only one line is in flight at a time.
itertools Essentials — Slice, Chain, Group and Total Lazily
islice, count, chain, groupby and accumulate: five tools that replace a pile of hand-written loops.
Writing Decorators — Wrap Functions Without Touching Them
Add logging, validation or retries to any function with one @ line — and keep its name and docstring intact.
Recursion Basics — Functions That Call Themselves
Every recursive function needs a base case that stops, and a step that makes the problem smaller.
Searching — Linear Scans, Binary Search and bisect
Check every item, or halve a sorted list each step: the second finds 1 in a million in 20 looks.
Hash-Map Patterns — Let a Dict Remember for You
Two-sum, anagram groups and reconciliations: store what you have seen, look it up instantly.
Prefix Sums — Answer Any Range Total in One Subtraction
Add things up once, then answer "how much between day 3 and day 9?" instantly, as often as you like.
Two Pointers & Sliding Windows — One Pass Instead of Two Loops
Walk two indexes through a list and turn slow nested loops into a single quick pass.
heapq — Top-K, Smallest-N and Priority Queues
Always grab the smallest item fast: leaderboards, cheapest-N and to-do lists ordered by urgency.
Grids & Matrices — Work with Rows, Columns and Neighbours
Seating plans, game boards, spreadsheets: master the list-of-lists moves you will use again and again.
Stack Patterns — Undo, Calculators, Paths and "Next Bigger"
A plain list with append and pop quietly solves undo buttons, calculators and "what comes next" questions.
String Algorithms — Palindromes, Word Flips and Run-Length Codes
The classic text puzzles, solved the Pythonic way — and each one teaches a move you will reuse.
Greedy & Intervals — Merge Meetings and Pick the Best Slots
Sort first, then make the obvious choice at each step — and learn when "obvious" goes wrong.
Combinatorics with itertools — Try Every Option Without Nested Loops
When the options are few, just try them all: itertools writes the nested loops for you.
Sorting by Hand — Insertion, Merge and Counting Sort
You will almost always call sorted() — but writing the sorts yourself teaches ideas that show up everywhere.
Counting the Cost — See Big-O by Counting Steps
Forget stopwatches: count the steps your code takes and watch how the count grows with the input.
Graph Search — Explore Networks with BFS and DFS
Friends of friends, train routes, maze escapes: one queue or one stack explores them all.
Dynamic Programming — Solve Big Problems from Small Answers
Stop recomputing the same thing: remember small answers and build the big one from them.