Overview
What is Python by Example?
Python by Example is a code-first tutorial series designed for experienced developers switching to Python or deepening their Python expertise. Instead of narrative explanations, you learn through 80 self-contained, heavily annotated, runnable examples that demonstrate Python concepts in action.
Why By-Example?
Traditional tutorials explain concepts with prose, then show code. By-example inverts this approach:
- Show the code first - Working, production-relevant examples
- Run it second - Every example is copy-paste-runnable
- Understand through interaction - Inline annotations reveal behavior
- Build pattern recognition - 80 examples create comprehensive mental models
This approach works best for developers who prefer learning through working code rather than reading documentation.
Learning Path
%% Color Palette: Blue #0173B2, Orange #DE8F05, Teal #029E73, Purple #CC78BC, Brown #CA9161
graph TD
A["Beginner<br/>Examples 1-27<br/>Python Fundamentals"] --> B["Intermediate<br/>Examples 28-54<br/>Production Patterns"]
B --> C["Advanced<br/>Examples 55-80<br/>Expert Mastery"]
style A fill:#0173B2,color:#fff
style B fill:#DE8F05,color:#fff
style C fill:#029E73,color:#fff
Progress from fundamentals through production patterns to expert mastery. Each level builds on the previous, increasing in sophistication and introducing more Pythonic idioms.
Coverage Philosophy
This tutorial provides comprehensive coverage of Python through practical, annotated examples. This tutorial covers core language features comprehensively, not a time estimate—focus is on outcomes and understanding, not duration.
What's Covered
Core Topics Covered:
- Core syntax and semantics (variables, operators, control flow)
- Built-in types and data structures (lists, dicts, sets, tuples)
- Functions, lambdas, and closures
- Object-oriented programming (classes, inheritance, magic methods)
- Modules and packages
- File I/O and context managers
- Exception handling and custom exceptions
- Decorators and descriptors
- Comprehensions and generators
- Itertools and functools
- Type hints and protocols
- Asyncio and concurrency
- Testing with pytest
- Standard library essentials (pathlib, collections, datetime, json)
- Virtual environments and packaging
What's NOT Covered
This guide focuses on learning-oriented examples, not problem-solving recipes or production deployment. For additional topics:
- CPython internals and C extensions - Implementation details beyond the language
- Rare standard library modules - aifc, sunau, uu, and other niche modules
- Platform-specific features - ctypes internals, Windows registry
- Deprecated features - imp module, old-style classes
- Framework internals - Django ORM source, Flask internals (covered at introductory level only)
The comprehensive coverage goal maintains humility—no tutorial can cover everything. This guide teaches the core concepts that continue learning beyond this tutorial through your own exploration and project work.
Tutorial Structure
80 examples across three levels:
- Beginner (Examples 1-27, fundamental concepts): Python fundamentals - variables, types, control flow, functions, basic data structures, simple OOP
- Intermediate (Examples 28-54, production patterns): Production patterns - modules, file I/O, exceptions, decorators, comprehensions, iterators, testing
- Advanced (Examples 55-80): Advanced mastery: Expert mastery - metaclasses, asyncio, context managers, generators, protocols, type hints, packaging, performance
Coverage percentages indicate depth and breadth of Python knowledge, not time investment.
Example Format
Every example follows a five-part format:
1. Brief Explanation (2-3 sentences)
Context and motivation for the concept:
### Example 15: List Comprehensions
List comprehensions provide a concise syntax for creating lists based on existing sequences, combining mapping and filtering in a single expression. They are more readable and often faster than equivalent for-loop constructions, making them a Pythonic way to transform data.2. Mermaid Diagram (when appropriate)
Visual representation for non-obvious concepts (30-50% of examples):
%% List comprehension flow
graph TD
A[Input List] --> B[For Each Element]
B --> C{Filter Condition?}
C -->|True| D[Transform Element]
C -->|False| B
D --> E[Add to Result]
E --> B
B --> F[Output List]
style A fill:#0173B2,color:#fff
style B fill:#DE8F05,color:#fff
style C fill:#CC78BC,color:#fff
style D fill:#029E73,color:#fff
style E fill:#029E73,color:#fff
style F fill:#0173B2,color:#fff
3. Heavily Annotated Code
Self-contained, runnable code with # => annotations showing outputs and states:
# Original list
numbers = [1, 2, 3, 4, 5] # => numbers is [1, 2, 3, 4, 5]
# List comprehension: squares of even numbers
squares = [x**2 for x in numbers if x % 2 == 0]
# => squares is [4, 16] (2^2=4, 4^2=16)
# Equivalent for-loop (for comparison)
squares_loop = [] # => squares_loop is []
for x in numbers: # => Iterates: 1, 2, 3, 4, 5
if x % 2 == 0: # => True for 2, 4
squares_loop.append(x**2)# => Appends 4, then 16
# => squares_loop is [4, 16]
print(squares) # => Output: [4, 16]
print(squares == squares_loop) # => Output: True4. Key Takeaway (1-2 sentences)
Essential insight distilled:
**Key Takeaway**: Use list comprehensions for simple transformations and filtering - they're more Pythonic and readable than equivalent loops, but switch to regular loops when logic becomes complex or requires multiple statements.How to Use This Tutorial
For Complete Beginners to Python
- Start with Beginner level (Examples 1-27)
- Run every example in a Python REPL or
.pyfile - Modify examples to test your understanding
- Progress to Intermediate when comfortable with basics
For Developers with Python Experience
- Skim Beginner to identify gaps
- Focus on Intermediate (Examples 28-54) for production patterns
- Deep-dive Advanced (Examples 55-80) for expert techniques
For Experienced Developers from Other Languages
- Review Beginner quickly to learn syntax differences
- Focus on Pythonic idioms in Intermediate
- Use Advanced as a reference for Python-specific features
Self-Containment Philosophy
Every example is copy-paste-runnable within its level scope:
- Beginner examples: Completely standalone - full imports, no dependencies on previous examples
- Intermediate examples: Assume beginner knowledge but include all necessary code to run
- Advanced examples: Assume beginner + intermediate concepts but remain fully runnable
Golden rule: If you delete all other examples, any single example should still run successfully.
Educational Annotations
Examples use # => notation to show:
- Variable states:
x = 10 # => x is 10 (type: int) - Outputs:
print(x) # => Output: 10 - Intermediate values:
y = x * 2 # => y is 20 (x remains 10) - Side effects:
lst.append(5) # => lst is now [1, 2, 3, 5] - Error cases:
int("bad") # => Raises ValueError: invalid literal for int()
These annotations make code behavior explicit without needing to run examples (though running them is encouraged!).
Diagram Guidelines
Diagrams use color-blind friendly palette:
- Blue (#0173B2): Primary elements, starting states
- Orange (#DE8F05): Processing states, operations
- Teal (#029E73): Success states, outputs
- Purple (#CC78BC): Conditional paths, options
- Brown (#CA9161): Neutral elements, helpers
This ensures accessibility for all learners.
Prerequisites
- Python 3.9+ installed (examples use modern Python features)
- Basic programming knowledge (variables, loops, functions in any language)
- Text editor or IDE (VS Code, PyCharm, or any editor)
- Terminal/command prompt access
Install Python from python.org or use your system package manager.
Running Examples
Option 1: Python REPL (Interactive)
python3
>>> # Paste example code hereOption 2: Script File
# Save example to example.py
python3 example.pyOption 3: Jupyter Notebook
pip install jupyter
jupyter notebook
# Create new notebook, paste examples in cellsLearning Strategies
For Java/C# Developers
You're used to static typing and verbose OOP. Python will feel liberating but initially unfamiliar:
- Dynamic typing: No type declarations required (though type hints are available)
- Duck typing: If it walks like a duck and quacks like a duck, it's a duck
- No braces: Indentation defines code blocks, whitespace matters
Focus on Examples 1-10 (Python basics) and Examples 40-45 (type hints) to bridge your static typing background.
For JavaScript/TypeScript Developers
You understand dynamic typing and async patterns. Python has similar flexibility:
- Similar feel: Dynamic typing, first-class functions, flexible syntax
- Different async model:
async/awaitworks similarly but with different event loop semantics - No
thisconfusion: Methods receiveselfexplicitly
Focus on Examples 55-65 (asyncio) and Examples 28-35 (decorators) to leverage your JS knowledge.
For C/C++ Developers
You understand systems programming and pointers. Python abstracts all of that:
- No manual memory: Garbage collection handles everything
- No pointers: References are implicit, everything is an object
- Slower but productive: Rapid development, slower execution
Focus on Examples 70-80 (performance optimization, C extensions) to understand when Python's abstractions matter.
For Ruby Developers
You know dynamic, expressive languages. Python is similar but more explicit:
- Explicit is better: No implicit returns, blocks, or magic methods (mostly)
- One way to do it: Python prefers single obvious solutions
- Significant whitespace: Indentation instead of
endkeywords
Focus on Examples 35-45 (comprehensions, generators) to see Python's expressive patterns.
Code-First Philosophy
This tutorial prioritizes working code over theoretical discussion:
- No lengthy prose: Concepts are demonstrated, not explained at length
- Runnable examples: Every example runs in Python REPL or as scripts
- Learn by doing: Understanding comes from running and modifying code
- Pattern recognition: See the same patterns in different contexts across 80 examples
If you prefer narrative explanations. By-example learning works best when you learn through experimentation.
What You'll Learn
By completing all 80 examples, you'll master:
- Python fundamentals: Syntax, types, control flow, functions
- Data structures: Lists, dicts, sets, tuples, and their methods
- Pythonic patterns: Comprehensions, generators, decorators, context managers
- Object-oriented Python: Classes, inheritance, magic methods, protocols
- Functional programming: Lambdas, map/filter/reduce, functools, itertools
- Concurrency: Asyncio, async/await, tasks, and event loops
- Error handling: Exceptions, custom errors, exception chaining
- Testing: Pytest, fixtures, parametrization, mocking
- Type safety: Type hints, protocols, generics, mypy
- Packaging: Modules, packages, virtual environments, pip, setup.py
Navigation
- Beginner - Examples 1-27 (fundamental concepts)
- Intermediate - Examples 28-54 (production patterns)
- Advanced - Examples 55-80 (advanced mastery)
Ready to learn Python through code? Start with Beginner examples!
Examples by Level
Beginner (Examples 1–27)
- Example 1: Hello World and Print
- Example 2: Variables and Dynamic Typing
- Example 3: Numbers and Arithmetic
- Example 4: Strings and String Methods
- Example 5: Boolean Logic and Comparisons
- Example 6: Conditional Statements (if/elif/else)
- Example 7: While Loops
- Example 8: For Loops and Range
- Example 9: Lists - Creation and Access
- Example 10: Lists - Modification Methods
- Example 11: Tuples - Immutable Sequences
- Example 12: Dictionaries - Key-Value Pairs
- Example 13: Sets - Unique Collections
- Example 14: Functions - Definition and Calls
- Example 15: Function Scope and Global Variables
- Example 16: Lambda Functions
- Example 17: List Comprehensions
- Example 18: Dictionary and Set Comprehensions
- Example 19: Exception Handling - Try/Except
- Example 20: File I/O - Reading and Writing
- Example 21: Classes - Basics
- Example 22: Classes - Inheritance
- Example 23: Class Properties and Magic Methods
- Example 24: Modules and Imports
- Example 25: String Formatting
- Example 26: Iterators and the Iterator Protocol
- Example 27: Basic Error Handling Patterns
Intermediate (Examples 28–54)
- Example 28: Basic Decorator
- Example 29: Decorator with Arguments
- Example 30: Preserving Function Metadata
- Example 31: Basic Generator
- Example 32: Generator Expression
- Example 33: Context Manager (with statement)
- Example 34: contextlib for Simple Context Managers
- Example 35: Regular Expression Matching
- Example 36: Regular Expression Groups and Substitution
- Example 37: JSON Serialization
- Example 38: CSV Reading and Writing
- Example 39: Pathlib for Modern File Operations
- Example 40: Collections - namedtuple
- Example 41: Collections - Counter
- Example 42: Collections - defaultdict
- Example 43: Collections - deque
- Example 44: functools - partial
- Example 45: functools - lru_cache
- Example 46: itertools - Powerful Iteration
- Example 47: Datetime Basics
- Example 48: Type Hints Basics
- Example 49: Dataclasses
- Example 50: Enums for Named Constants
- Example 51: Abstract Base Classes
- Example 52: Basic pytest Tests
- Example 53: pytest Fixtures
- Example 54: pytest Parametrize
Advanced (Examples 55–80)
- Example 55: Basic Metaclass
- Example 56: init_subclass (Simpler Alternative)
- Example 57: Descriptor Protocol
- Example 58: Property as Descriptor
- Example 59: Asyncio Basics
- Example 60: Asyncio Tasks
- Example 61: Async Context Managers
- Example 62: Protocol (Structural Subtyping)
- Example 63: Generic Types
- Example 64: Profiling with cProfile
- Example 65: Memory Profiling
- Example 66: Threading for I/O-Bound Tasks
- Example 67: ThreadPoolExecutor
- Example 68: Multiprocessing for CPU-Bound Tasks
- Example 69: Weak References
- Example 70: Context Variables for Async Context
- Example 71: Advanced Decorators - Class Decorators
- Example 72: Introspection with inspect
- Example 73: Dynamic Code Execution
- Example 74: AST Module for Code Analysis
- Example 75: Packaging with pyproject.toml
- Example 76: Advanced pytest - Mocking
- Example 77: pytest Markers for Test Organization
- Example 78: Singleton Pattern (Pythonic)
- Example 79: Observer Pattern
- Example 80: Best Practices - EAFP and Duck Typing
Last updated December 29, 2025