Full index · 39 tutorials
All Python tutorials
Every tutorial published on Pyford Notes, in one place. Each one starts from a real problem, shows the working code, and explains the tradeoffs so you know when to reach for the pattern again.
All tutorials
-
Core Syntax
The Walrus Operator (:=): Assignment Expressions in Python
What := does, why it exists, and the while-loop and comprehension patterns where it removes real duplication.
-
Standard Library
functools Essentials: reduce(), partial(), lru_cache, and wraps
A practical tour of functools: folding sequences with reduce, pre-filling arguments with partial, and caching with lru_cache.
-
OOP
Property Decorators in Python: @property, Getters, and Setters
How @property turns a method call into attribute access, and how @x.setter adds validation without changing the calling interface.
-
OOP
Operator Overloading in Python: Dunder Methods Like __add__ and __eq__
How Python maps operators like + and == onto dunder methods, and how to give your own classes sensible operator support.
-
Iteration
Iterators and the Iterator Protocol: How __iter__ and __next__ Really Work
How Python's for loop actually works under the hood, and how to build your own iterator class using __iter__ and __next__.
-
Error Handling
Python Error Messages and Tracebacks: How to Read Them Fast
How to read a Python traceback from bottom to top, what the exception type tells you, chained exceptions, and quick habits for finding the real cause of a bug.
-
Standard Library
Command-Line Arguments in Python: sys.argv and argparse
Reading raw command-line arguments with sys.argv, and building a proper CLI with argparse covering positional args, optional flags, defaults, and help text.
-
Standard Library
Python Logging: Replacing print() Debugging With logging
Why the logging module scales better than scattered print() calls, log levels, basicConfig, named loggers per module, and writing log output to a file.
-
Functions
Recursion in Python: How It Works and When to Avoid It
How a recursive function calls itself, base cases, the call stack, Python's recursion limit, and when an iterative or memoised approach is the better choice.
-
Core Syntax
Python Comparison and Identity: == vs is, and How Equality Really Works
The difference between == (value equality) and is (identity), how __eq__ controls == for custom objects, comparing with None, and integer-interning caveats.
-
Core Syntax
Multiple Assignment and Unpacking in Python: Tuples, Stars, and Swaps
Assigning multiple variables at once, unpacking any iterable, the star operator for collecting extra items, and the classic variable-swap idiom.
-
Built-ins
Python Sorting: sorted(), sort(), and Custom Keys
The difference between sorted() and list.sort(), the key= parameter, sorting by multiple criteria, reverse order, and Python's sort stability guarantee.
-
Core Syntax
Slicing in Python: Beyond the Basics of start:stop:step
Slice syntax on lists and strings, negative indices, step values including reversal, slice assignment, and the built-in slice() object.
-
Tooling
Python Modules and Packages: Organizing Code Across Files
How import works, the difference between a module and a package, __init__.py, different import forms, and the guard that checks whether a module is being run directly.
-
OOP
Inheritance and Polymorphism in Python: Extending Classes Cleanly
Subclassing, overriding methods, using super() to extend rather than replace parent behaviour, duck-typing polymorphism, and isinstance checks.
-
OOP
Python Classes and OOP Basics: Attributes, Methods, and __init__
Defining a class, the role of __init__ and self, instance attributes versus class attributes, and writing methods that operate on an object's own state.
-
Functions
Python Functions: Default Arguments, Scope, and Closures
Default argument evaluation timing, the LEGB scope rule, the nonlocal keyword, and how closures capture variables from an enclosing scope.
-
Core Syntax
Python String Methods: A Practical Reference for Everyday Text Processing
Covers searching (find/index/startswith), splitting and joining, stripping, replacing with translate, case conversion, and content-testing predicates.
-
Standard Library
datetime in Python: Dates, Times, Arithmetic, and Timezones
Construct date and datetime objects, perform timedelta arithmetic, format with strftime, parse with strptime, and understand naive vs aware timezones.
-
Standard Library
JSON Handling in Python: Serialising, Deserialising, and Edge Cases
Covers json.loads, json.load, json.dumps with indent, custom encoders for non-serialisable types, and pitfalls around key types and float precision.
-
Standard Library
itertools in Python: Memory-Efficient Iteration Without Manual Loops
itertools provides building blocks for iterator algebra: chain, islice, groupby, product, combinations, and more — all lazy, all composable.
-
Standard Library
The collections Module: Specialised Containers Beyond list and dict
Counter, defaultdict, deque, namedtuple, and OrderedDict each solve a specific data-structure problem more cleanly than a plain list or dict.
-
Modern Python
Python Dataclasses: Auto-Generated __init__, __repr__, and More
@dataclass generates boilerplate methods from field annotations. Covers field defaults, __post_init__ validation, frozen instances, and comparison with NamedTuple.
-
Standard Library
pathlib in Python: File Paths as Objects, Not Strings
The pathlib module replaces os.path string juggling with an object-oriented API. Create, navigate, read, write, and glob file paths cross-platform.
-
Functions
Lambda Functions in Python: Anonymous One-Liners and Where They Shine
A lambda is a small anonymous function defined in a single expression. Covers sorting key= usage, map/filter, conditional expressions, and when a named def is clearer.
-
Built-ins
enumerate() and zip() in Python: Loop Over Multiple Sequences Cleanly
enumerate() adds an index counter without range(len()), and zip() pairs sequences in lockstep. Together they cover nearly every parallel-iteration pattern.
-
Data Structures
Sets and Frozensets in Python: Unordered Collections with Powerful Maths
Sets hold only unique values and support O(1) membership testing. Covers set arithmetic operators, set comprehensions, and frozensets for hashable immutable needs.
-
Functions
*args and **kwargs in Python: Flexible Function Signatures Explained
Collecting variable positional and keyword arguments, unpacking sequences and dicts at the call site, and keyword-only parameter syntax.
-
Standard Library
Regular Expressions in Python: Patterns, Groups, and the re Module
Pattern syntax, search vs match, capturing groups, named groups, flags, substitution, and when NOT to reach for regex.
-
Resource Management
Context Managers in Python: with Statements and the Protocol Behind Them
The __enter__/__exit__ protocol, writing your own manager as a class or with contextlib.contextmanager, and suppressing exceptions cleanly.
-
Modern Python
Type Hints in Python: Annotate Code Without Changing Its Behaviour
Optional annotations that static checkers and IDEs use to catch bugs. Covers Optional, Union, generics, and what happens at runtime.
-
Data Structures
Dictionary Techniques in Python: Beyond Basic Key-Value Storage
Dict comprehensions, defaultdict, safe access with get() and setdefault(), the | merge operator, and Counter for frequency counting.
-
Standard Library
Working with Files in Python: Reading, Writing, and Paths
Open modes, line-by-line iteration, pathlib for path manipulation, and why the with statement is the only safe way to handle file objects.
-
Error Handling
Exception Handling in Python: try, except, else, finally
Catching specific types, the role of else and finally, raising meaningful errors, and building a custom exception hierarchy.
-
Core Syntax
f-Strings Formatting: Everything You Can Put Inside the Braces
Beyond variable interpolation: alignment, number specs, debug output with =, and the full format mini-language inside curly braces.
-
Tooling
Virtual Environments with venv: Project Isolation Step by Step
Each project gets its own dependency tree. How to create, activate, install into, and reproduce a venv environment reliably.
-
Iterators
Generators and yield: Sequences That Pay as They Go
Why loading a million rows into a list is unnecessary. How yield pauses a function and resumes it on demand, keeping memory flat.
-
Functions
Decorators Explained: Wrap Functions Without Touching Them
How decorators borrow function objects, add behaviour around them, and return a modified callable. Built step by step from first principles.
-
Core Syntax
List Comprehensions: Build Lists Without the Loop Noise
Transform, filter, and flatten sequences in one readable expression. When comprehensions help and when a plain loop is the better choice.