HomeAll tracks · pricing · account
Python11 apps · Python, SQL & data
Start free Log in

BitSize Python · Recipes

Python Recipes.

The everyday Python patterns, run right in your browser.

recipe.py

        

Track your progress

Save where you are and see what you remember.

Sign up free →
📝 Strings, numbers & decisions 16
#1📝

String Literals — Four Kinds, One Mission

Single, double, raw, and triple-quoted strings each exist for a reason. Know when to use each.

Starter5 tasks Up next →
#2🎨

f-String Basics — Interpolate Anything in One Shot

f'{variable}' injects a value. f'{expression}' evaluates any expression. f'{obj.method()}' calls methods inline.

Starter5 tasks Free account →
#3🔢

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.

Starter5 tasks Free account →
#4📐

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.

Starter5 tasks 🔒 Subscribe
#5✂️

str.split() and rsplit() — Break Text Apart

split() divides on whitespace or a delimiter. rsplit() starts from the right. maxsplit limits how many cuts.

Starter5 tasks 🔒 Subscribe
#6🔗

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.

Starter5 tasks 🔒 Subscribe
#7🧹

strip, replace, count — The Daily Cleaning Trio

strip() removes edge characters. replace() substitutes text. count() finds occurrences. Three methods, endless utility.

Starter5 tasks 🔒 Subscribe
#8🔎

startswith / endswith — Test Prefixes and Suffixes

endswith(('.jpg','.png')) checks multiple extensions in one call. No 'or' chains needed.

Starter5 tasks 🔒 Subscribe
#9🔍

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.

Starter5 tasks 🔒 Subscribe
#10🔢

Integer Operations — //, %, **, divmod()

// is floor division. % is remainder. ** is power. divmod() gives both at once. Together they solve a huge range of problems.

Starter5 tasks 🔒 Subscribe
#11🌊

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.

Starter5 tasks 🔒 Subscribe
#12✅

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.

Starter5 tasks 🔒 Subscribe
#13⚡

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.

Starter5 tasks 🔒 Subscribe
#14🎯

Ternary Expression — if/else in One Line

value = x if condition else y. Works inside comprehensions, f-strings, and return statements.

Starter5 tasks 🔒 Subscribe
#15🦭

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.

Starter5 tasks 🔒 Subscribe
#16🧩

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.

Starter5 tasks 🔒 Subscribe
📋 Collections — lists, sets, dicts 17
#17📋

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.

Starter5 tasks 🔒 Subscribe
#18✂️

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.

Starter5 tasks 🔒 Subscribe
#19➕

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.

Starter4 tasks 🔒 Subscribe
#20🪞

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.

Starter5 tasks 🔒 Subscribe
#21🏆

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.

Starter5 tasks 🔒 Subscribe
#22🔢

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.

Starter4 tasks 🔒 Subscribe
#23🤐

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.

Starter5 tasks 🔒 Subscribe
#24📦

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'.

Starter5 tasks 🔒 Subscribe
#25✅

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.

Starter4 tasks 🔒 Subscribe
#26🔵

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.

Starter4 tasks 🔒 Subscribe
#27⚙️

Set Operations — &, |, -, ^ — Think in Groups

& is intersection (in both), | is union (in either), - is difference (left only), ^ is symmetric difference (in exactly one).

Starter5 tasks 🔒 Subscribe
#28🔑

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.

Starter4 tasks 🔒 Subscribe
#29👁️

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.

Starter5 tasks 🔒 Subscribe
#30🏷️

namedtuple, NamedTuple & Enum — Lightweight Records

Stop writing row[2] and 'shipped' strings: give tuple fields names and fixed choices a proper type.

Starter5 tasks 🔒 Subscribe
#31🧮

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.

Starter5 tasks 🔒 Subscribe
#32🪆

Nested Dicts & Merging — Combine Settings Safely

Merge dicts with |, fill gaps with setdefault, and read deep keys without a single KeyError.

Simmering5 tasks 🔒 Subscribe
#33📚

Stacks & Queues — list for LIFO, deque for FIFO

Undo buttons are stacks, print jobs are queues. Python gives you both in two lines.

Starter5 tasks 🔒 Subscribe
⚙️ Comprehensions, functions & errors 17
#34⚡

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.

Starter5 tasks 🔒 Subscribe
#35🗃️

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.

Starter5 tasks 🔒 Subscribe
#36🧩

Conditional & Nested Comprehensions — Filter, Transform, Pair

An if at the end filters. An if/else at the front transforms. Two fors make every pair.

Starter5 tasks 🔒 Subscribe
#37📦

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.

Starter5 tasks 🔒 Subscribe
#38📤

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.

Starter5 tasks 🔒 Subscribe
#39🐛

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.

Starter4 tasks 🔒 Subscribe
#40🔀

*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.

Starter5 tasks 🔒 Subscribe
#41🔐

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.

Starter4 tasks 🔒 Subscribe
#42🎯

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.

Simmering5 tasks 🔒 Subscribe
#43λ

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.

Starter5 tasks 🔒 Subscribe
#44📦

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.

Simmering5 tasks 🔒 Subscribe
#45🛠️

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.

Simmering5 tasks 🔒 Subscribe
#46🛡️

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.

Starter5 tasks 🔒 Subscribe
#47⚠️

Catching Multiple Exceptions — Tuples and Re-raising

except (A, B) catches either. 'raise' re-raises the current exception. 'raise X from Y' chains exceptions.

Starter4 tasks 🔒 Subscribe
#48🚨

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.

Simmering5 tasks 🔒 Subscribe
#49🔎

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.

Starter5 tasks 🔒 Subscribe
#50✅

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.

Simmering5 tasks 🔒 Subscribe
📁 Text, files & data 13
#51🧽

Text-Cleaning Pipeline — From Messy Text to Word Stats

Lowercase, strip punctuation, split into words, count them. The four steps behind every word cloud.

Simmering5 tasks 🔒 Subscribe
#52🔤

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.

Simmering5 tasks 🔒 Subscribe
#53🔢

Number Bases & Bitwise Operators — Think in Binary

Read binary and hex, flip bits with & | ^ << >>, and pack yes/no permissions into a single number.

Simmering5 tasks 🔒 Subscribe
#54🧾

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.

Simmering5 tasks 🔒 Subscribe
#55🕵️

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.

Simmering5 tasks 🔒 Subscribe
#56🧽

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.

Simmering5 tasks 🔒 Subscribe
#57📄

Text Files with `with` — Write, Read, Append Safely

open() inside a with block: the file is always closed, even if something goes wrong.

Starter5 tasks 🔒 Subscribe
#58📂

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.

Simmering5 tasks 🔒 Subscribe
#59🗃️

CSV & JSON — Save and Load Real Data Files

Spreadsheets and settings in, summaries out: the two file formats you will meet every week.

Simmering5 tasks 🔒 Subscribe
#60🪆

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.

Simmering5 tasks 🔒 Subscribe
#61📊

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.

Simmering5 tasks 🔒 Subscribe
#62📅

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.

Simmering5 tasks 🔒 Subscribe
#63🧮

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.

Simmering5 tasks 🔒 Subscribe
🏗️ Classes 8
#64🏗️

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.

Starter5 tasks 🔒 Subscribe
#65🔐

Properties & Class Attributes — Smart Attributes, Shared State

Computed values that read like attributes, setters that refuse bad data, and counters every object shares.

Simmering5 tasks 🔒 Subscribe
#66✨

Dunder Methods — Make Your Objects Feel Built-in

Teach your classes to print nicely, compare by value, sort, and answer len().

Simmering5 tasks 🔒 Subscribe
#67🧬

Inheritance & super() — Reuse a Class, Change What Differs

Child classes inherit everything, override only what changes, and call super() for the rest.

Simmering5 tasks 🔒 Subscribe
#68📦

Dataclasses — Classes Without the Boilerplate

List the fields, add @dataclass, and get __init__, a readable repr and == for free.

Starter5 tasks 🔒 Subscribe
#69🦆

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.

Head Chef5 tasks 🔒 Subscribe
#70🔁

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.

Simmering5 tasks 🔒 Subscribe
#71🚪

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.

Head Chef5 tasks 🔒 Subscribe
🧮 Problem-solving patterns 15
#76🔁

Recursion Basics — Functions That Call Themselves

Every recursive function needs a base case that stops, and a step that makes the problem smaller.

Simmering5 tasks 🔒 Subscribe
#77🔎

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.

Simmering5 tasks 🔒 Subscribe
#78🗂️

Hash-Map Patterns — Let a Dict Remember for You

Two-sum, anagram groups and reconciliations: store what you have seen, look it up instantly.

Simmering5 tasks 🔒 Subscribe
#79📈

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.

Simmering5 tasks 🔒 Subscribe
#80👉

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.

Head Chef5 tasks 🔒 Subscribe
#81⛰️

heapq — Top-K, Smallest-N and Priority Queues

Always grab the smallest item fast: leaderboards, cheapest-N and to-do lists ordered by urgency.

Simmering5 tasks 🔒 Subscribe
#82🔲

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.

Simmering5 tasks 🔒 Subscribe
#83🥞

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.

Simmering5 tasks 🔒 Subscribe
#84🔤

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.

Simmering5 tasks 🔒 Subscribe
#85📅

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.

Simmering5 tasks 🔒 Subscribe
#86🎲

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.

Simmering5 tasks 🔒 Subscribe
#87🗂️

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.

Head Chef5 tasks 🔒 Subscribe
#88⏱️

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.

Head Chef4 tasks 🔒 Subscribe
#89🕸️

Graph Search — Explore Networks with BFS and DFS

Friends of friends, train routes, maze escapes: one queue or one stack explores them all.

Head Chef5 tasks 🔒 Subscribe
#90🧗

Dynamic Programming — Solve Big Problems from Small Answers

Stop recomputing the same thing: remember small answers and build the big one from them.

Head Chef5 tasks 🔒 Subscribe