Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
Chain Generators with yield from in Python
Combine multiple generators into one seamless sequence using the `yield from` delegation syntax in Python.
def numbers():
yield 1
yield 2
yield 3
def letters():
yield 'a'
yield 'b'
yield 'c'
def combined():
yield from numbers()
yield from letters()
if __name__ == "__main__":
print(list(combined()))
How to Compose Two Functions into a Single Callable in Python
Combine two Python functions into a single callable using a compose helper, then apply the chained call.
def add_one(x):
return x + 1
def double(x):
return x * 2
def compose(f, g):
return lambda x: f(g(x))
add_then_double = compose(double, add_one)
double_then_add = compose(add_one, double)
result1 = add_then_double(5)
result2 = double_then_add(5)
print(f"add_one then double(5) = {result1}")
print(f"doub…
Collect Multiple Validation Errors in Python Before Raising
A chainable Validator class that accumulates all validation errors and raises them together in a single exception.
class ValidationError(Exception):
pass
class Validator:
def __init__(self):
self.errors = []
def validate_required(self, value, field_name):
if not value:
self.errors.append(f"{field_name} is required")
return self
def validate_email(self, email):
…
How to Print an Exception Chain in Python for Debugging
A helper that walks an exception's __cause__ and __context__ chain, printing each level with indentation to make debugging nested errors clearer.
import sys
import traceback
def pretty_exception_chain(exc):
"""Print the full exception chain with cause/context details."""
chain = []
current = exc
seen = set()
while current is not None and id(current) not in seen:
seen.add(id(current))
chain.append(current)
curren…
How to Re-raise Exceptions with 'raise from' in Python
Shows how to re-raise an exception with explicit context chaining using the 'raise ... from ...' syntax, so the original cause is preserved for debugging.
def divide_with_chain(a, b):
try:
result = a / b
return result
except ZeroDivisionError as original_error:
# Re-raise with explicit chaining context
raise ValueError("Cannot divide by zero") from original_error
def explain_chain():
try:
divide_with_chain(10, 0)
…
How to Wrap a Low Level Error in a Higher Level Exception in Python
Wrap low-level exceptions in a higher-level exception while preserving the original cause with the `from` keyword.
class LowLevelError(Exception):
pass
class HighLevelError(Exception):
pass
def low_level_operation():
raise LowLevelError("storage drive failed to respond")
def high_level_operation():
try:
low_level_operation()
except LowLevelError as e:
raise HighLevelError(f"database operation…
How to Use ChainMap for Layered Config Lookup in Python
This code demonstrates using collections.ChainMap to combine multiple dictionaries into a single layered lookup, where earlier maps override later ones.
from collections import ChainMap
defaults = {"theme": "light", "lang": "en", "debug": False}
user = {"lang": "de", "auto_save": True}
runtime = {"debug": True}
config = ChainMap(runtime, user, defaults)
if __name__ == "__main__":
print("theme:", config["theme"])
print("lang:", config["lang"])
print("deb…
How to Build a Fluent Interface with the Builder Pattern in Python
Learn to implement a fluent builder pattern in Python by chaining methods that return self, enabling readable object construction.
class Pizza:
def __init__(self):
self.size = None
self.toppings = []
self.crust = None
def set_size(self, size):
self.size = size
return self
def add_topping(self, topping):
self.toppings.append(topping)
return self
def set_crust(self, crust):
…
How to Call a Parent Class __init__ with super() in Python
Shows how to chain __init__ calls through a class hierarchy using super(), so each class sets its own attributes while reusing the parent's initialization logic.
class Animal:
def __init__(self, name, species):
self.name = name
self.species = species
print(f"Animal init: {self.name}, {self.species}")
class Mammal(Animal):
def __init__(self, name, species, fur_color):
super().__init__(name, species)
self.fur_color = fur_color
…
How to Implement the State Pattern in Python
Implement the State design pattern in Python by delegating behavior to state objects, letting a media player change actions dynamically without if-else chains.
class State:
def play(self, player): pass
def pause(self, player): pass
def stop(self, player): pass
class PlayingState(State):
def play(self, player):
return "Already playing"
def pause(self, player):
player.state = PausedState()
return "Pausing playback"
def stop(self…
Build a Generator Pipeline in Python: Filter Then Map
Create a lazy data pipeline by chaining generator functions that read, filter, map, and write data step by step.
def read_data():
return ["a", "bb", "ccc", "dd", "eeeee", "f"]
def filter_short(words):
return (word for word in words if len(word) >= 2)
def map_to_upper(words):
return (word.upper() for word in words)
def write_data(words):
for word in words:
print(word)
if __name__ == "__main__":
…
How to Merge Multiple Iterables with a Generator in Python
This code defines a generator function that 'chains' or merges multiple iterables into a single iterator, which is then converted to a list.
def chain(*iterables):
for iterable in iterables:
yield from iterable
def main():
list1 = [1, 2, 3]
tuple1 = (4, 5)
set1 = {6, 7}
string1 = "89"
result = list(chain(list1, tuple1, set1, string1))
print(result)
if __name__ == "__main__":
main()
Chain of Thought Prompting in Python: Step-by-Step Reasoning Demo
This demo shows how to structure a function that explains its own reasoning step-by-step, mimicking chain-of-thought prompting for AI systems.
def solve_math_step_by_step(expression: str) -> str:
"""Solves a simple expression, showing each reasoning step."""
# Step 1: Parse the expression (assume "a + b" or "a - b")
parts = expression.split()
a = int(parts[0])
op = parts[1]
b = int(parts[2])
steps = []
steps.append(f"Step…
Detect Circular Imports Across Python Projects Automatically
This script walks through all .py files in a directory, builds an import graph, and uses depth-first search to find cycles—printing each circular dependency chain.
import ast
import sys
from pathlib import Path
from collections import defaultdict, deque
def find_imports(filepath):
"""Return set of module names imported by a Python file."""
imports = set()
try:
with open(filepath) as f:
tree = ast.parse(f.read())
except (SyntaxError, UnicodeDe…
Cross Account Role Chaining Mock Credentials in Python
Simulate AWS STS AssumeRole with mock credentials for cross-account role chaining in Python.
import json
class CredentialChain:
def __init__(self, account_id, role_name):
self.account_id = account_id
self.role_name = role_name
self.credentials = {}
def assume_role(self, session_name="mock_session"):
"""Simulate STS AssumeRole, returning mock credentials with expiry.""…
How to Build a Chainable Filter Helper in Python
A beginner-friendly dataclass helper that chains filters, uniqueness, and slicing on any sequence, returning a plain list at the end.
from dataclasses import dataclass
from typing import Callable, Iterator, Sequence, TypeVar
T = TypeVar("T")
@dataclass
class FilterAssistant:
"""Beginner-friendly helper to filter any collection."""
data: Sequence[T]
def where(self, predicate: Callable[[T], bool]) -> "FilterAssistant":
return …
How to Build a Pipe and Filter Text Processing Chain in Python
A functional pipe-and-filter chain that transforms text through uppercase, whitespace normalization, number removal, stopword filtering, and file export.
import re
import sys
def pipe_filter_chain(stream):
def uppercase(text):
return text.upper()
def strip_whitespace(text):
return " ".join(text.split())
def remove_numbers(text):
return re.sub(r"\d+", "", text)
def remove_stopwords(text, stopwords={"the", "and", "of", "in"}):…
How to Build an sklearn Pipeline with ColumnTransformer in Python
A mock example showing how to chain preprocessing and a regression model into a single sklearn Pipeline, scaling numeric features and one-hot encoding categorical features with ColumnTransformer.
import numpy as np
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LinearRegression
# Mock dataset
X = np.array([[1, 'red'], [2, 'blue'], [3, 'red'], [4, 'green'], [5, 'blue']], dtype=o…
How to Define Dagster ML Assets in Python
Define a chain of Dagster software-defined assets that compute raw features, normalized features, and predictions for an ML pipeline.
from dagster import asset
@asset
def raw_features():
return {"sepal_length": [5.1, 4.9, 6.2], "sepal_width": [3.5, 3.0, 3.4]}
@asset
def normalized_features(raw_features):
values = raw_features["sepal_length"]
mean = sum(values) / len(values)
std = (sum((x - mean) ** 2 for x in values) / len(values…
How to Mock a Kubeflow Pipeline in Python
Build a minimal in-memory mock of a Kubeflow pipeline DAG using dataclasses and OrderedDict to chain component functions.
from typing import Dict, Any
from dataclasses import dataclass, field
from collections import OrderedDict
@dataclass
class KubeflowPipelineMock:
"""A minimal mock of a Kubeflow pipeline DAG."""
name: str
components: OrderedDict[str, callable] = field(default_factory=OrderedDict)
def add_component(se…
Browse by section
Each section groups closely related Python snippets.
Guide: free Python code samples library
Copy-ready Python snippets for learners and developers
PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.
How to use this library
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- Run it in the IDE, tweak values, then take a related quiz or tutorial lesson
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.