Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Speed Up Data Filtering with Python ThreadPoolExecutor
This code compares sequential filtering of even numbers with a threaded version using ThreadPoolExecutor, showing a measurable speedup for I/O-bound work.
import time
from concurrent.futures import ThreadPoolExecutor
import random
def is_even(number):
time.sleep(0.001) # simulate work
return number % 2 == 0
def filter_even_sequential(numbers):
return [n for n in numbers if is_even(n)]
def filter_even_threaded(numbers):
with ThreadPoolExecutor(max_…
How to Filter Data in Python with Type Hints
A reusable filter_data helper uses optional predicates and numeric bounds with modern Python type hints.
from typing import Iterable, TypeVar, Callable, Any
T = TypeVar("T")
def filter_data(
items: Iterable[T],
predicate: Callable[[T], bool] | None = None,
*,
min_value: float | None = None,
max_value: float | None = None,
) -> list[T]:
"""Filter items by predicate and/or numeric bounds."""
r…
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 Implement a Data Helper Class in Python
Build a beginner-friendly DataHelper class using dataclasses and key system design patterns like Command, Strategy, and Map.
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional
@dataclass
class DataHelper:
"""A beginner-friendly data utility with common system design patterns."""
data: List[Dict[str, Any]] = field(default_factory=list)
def add_record(self, r…
How to Build a Data Helper Class in Python for Beginners
Create a beginner-friendly DataHelper class that stores, retrieves, filters, and summarizes records in a list of dictionaries.
from __future__ import annotations
import json
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional
@dataclass
class DataHelper:
"""A beginner-friendly helper for common data tasks."""
data: List[Dict[str, Any]] = field(default_factory=list)
def add_record(self, record…
How to Build a Simple Filter Helper in Python for API Design
Create a reusable data filter service with dataclasses that mimics gRPC request/response patterns for filtering dataset records.
from dataclasses import dataclass, field
from typing import List, Optional, Dict, Any
@dataclass
class FilterRequest:
"""A simple filter request mirroring a gRPC message structure."""
field_name: str
operator: str # eq, ne, gt, lt, contains
value: Any
page_size: int = 10
page_token: Optional…
How to Filter Query Parameters by Operator in Python
Parse a URL query string and keep only parameters with allowed comparison operators like eq, gt, and lt.
from urllib.parse import urlparse, parse_qs
def filter_operators(query_string, allowed=("eq", "gt", "lt")):
parsed = urlparse(query_string)
params = parse_qs(parsed.query)
filtered = {}
for key, values in params.items():
if "__" in key:
field, op = key.rsplit("__", 1)
i…
How to Implement Sparse Fieldsets in Python
A function that filters API responses by resource type, returning only requested fields plus IDs, as a sparse fieldset mock.
from dataclasses import dataclass, field
from typing import Dict, List, Optional
@dataclass
class MockResponse:
data: Dict[str, object] = field(default_factory=dict)
included: List[Dict[str, object]] = field(default_factory=list)
def select_fields(
data: Dict[str, object],
sparse_fields: Optional[D…
Return Proper HTTP Status Codes Table in Python
Mock HTTP status code table with proper numeric and textual representations, including formatted status lines and a filtered table view.
# Mock HTTP status code table with proper numeric and textual representations
codes = {
200: "OK",
201: "Created",
204: "No Content",
301: "Moved Permanently",
302: "Found",
304: "Not Modified",
400: "Bad Request",
401: "Unauthorized",
403: "Forbidden",
404: "Not Found",
50…
Dedupe processed message IDs in Python
Filters an inbox of messages by removing items whose IDs have already been processed, using a set for fast lookups.
from pathlib import Path
import json
def dedupe_processed_ids(inbox_file: Path, processed_file: Path) -> list:
processed = set(json.loads(processed_file.read_text()))
inbox = json.loads(inbox_file.read_text())
deduped = [item for item in inbox if item["id"] not in processed]
return deduped
if __nam…
How to Build a Bloom Filter to Reduce Cache Misses in Python
Implement a probabilistic Bloom filter in Python that lets a cache quickly determine which keys are definitely not present, reducing expensive source lookups on cache misses.
import hashlib
import random
class BloomFilter:
def __init__(self, size=100, num_hashes=3):
self.size = size
self.num_hashes = num_hashes
self.bit_array = [0] * size
def _hashes(self, item):
result = []
for i in range(self.num_hashes):
hash_value = int(hash…
How to cache filtered data in Redis with Python
This code caches filtered list results in Redis using an MD5 hash key, returning cached results when available.
import redis
import json
import hashlib
import time
cache = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)
def filter_data(data, predicate_key, predicate_value):
"""Filter a list of dicts by key-value pair, with Redis caching."""
cache_key = hashlib.md5(
f"{predicate_key}:{pred…
How to Use Log Levels DEBUG INFO WARNING ERROR in Python
Demonstrates Python's logging levels (DEBUG, INFO, WARNING, ERROR) with basicConfig and a logger, showing how severity filtering controls output.
import logging
# Configure a mock logger to demonstrate log levels
logging.basicConfig(level=logging.DEBUG, format="%(levelname)s: %(message)s")
logger = logging.getLogger("mock_logger")
# Simulate events at each severity level
logger.debug("Detailed diagnostic info")
logger.info("General system operation")
logger.w…
Bloom Filter Join Mock in Python
A mock hash join that uses a Bloom filter to pre-filter one table before performing an exact match, reducing the number of comparisons in large dataset joins.
import hashlib
import random
import string
class BloomFilter:
def __init__(self, size: int = 200, num_hashes: int = 3):
self.bits = [False] * size
self.size = size
self.num_hashes = num_hashes
def _hashes(self, item: str):
result = []
for seed in range(self.num_hashes…
How to Filter and Project Spark DataFrames with PySpark SQL
Simulate a SQL SELECT with WHERE using PySpark DataFrame select and filter to project columns and apply conditions.
from pyspark.sql import SparkSession
from pyspark.sql.functions import col
spark = SparkSession.builder.appName("QueryFilterMock").master("local[2]").getOrCreate()
data = [
("Alice", 28, "Engineering"),
("Bob", 35, "Sales"),
("Carol", 32, "Engineering"),
("David", 25, "Marketing"),
("Eve", 29, "E…
How to Mock Partition Pruning in Python
A dataclass-based mock that filters partitions by year and month to emulate Spark's partition pruning logic.
from dataclasses import dataclass
from typing import List
@dataclass(frozen=True)
class Partition:
id: int
year: int
month: int
class PartitionPruner:
"""Mock partition pruning: only keep partitions that match the filter."""
def __init__(self, partitions: List[Partition]):
self._partiti…
Mock Predicate Pushdown in Python for Big Data Queries
Simulate predicate pushdown by applying filters at the storage layer before materializing rows, showing how big data engines optimize queries.
class Query:
def __init__(self, table, rows):
self.table = table
self.rows = rows
def filter(self, predicate):
return Query(
self.table,
[row for row in self.rows if all(predicate(row) for predicate in predicate)]
)
def filter_pushdown(self, predica…
Mock RDD in Python: Simulate Spark RDD Lazy Transformations
Simulate Apache Spark RDD behavior in Python with lazy maps, filters, partitions, and a collect action.
import random
def mock_rdd(data, num_slices=2):
"""
A simple simulation of Spark RDD behavior with lazy evaluation,
transformations, and an action.
"""
class SimpleRDD:
def __init__(self, data, num_slices=2):
self.data = data
self.num_slices = num_slices
…
Build a Data Helper Class in Python for ML Pipelines
A beginner-friendly Python class that summarizes, filters, and exports ML dataset rows as JSON.
from typing import List, Dict, Any
import json
class DataHelper:
"""Beginner-friendly helpers for ML data pipelines."""
def __init__(self, data: List[Dict[str, Any]]):
self.data = data
self.keys = list(data[0].keys()) if data else []
def summary(self) -> Dict[str, Any]:
"…
Build a Partial Index Mock in Python for Database Filtering
Simulate a partial database index by filtering keys with a predicate, then return a limited mock lookup dictionary.
data = [
"alpha", "beta", "gamma", "delta", "epsilon",
"zeta", "eta", "theta", "iota", "kappa"
]
filtered_keys = [item for item in data if len(item) >= 5]
def mock_partial_index(keys, filter_func, limit=3):
result = {}
for key in keys:
if not filter_func(key):
continue
res…
How to Create a Data Helper Class in Python for JSON Files
Build a beginner-friendly Python helper class to read, write, filter, and summarize JSON data files with clean, reusable methods.
import json
from pathlib import Path
class DataHelper:
"""Simple beginner-friendly helper for reading and writing JSON data files."""
@staticmethod
def read_json(filename):
file_path = Path(filename)
if file_path.exists():
with file_path.open("r", encoding="utf-8") as f:
…
How to mock DNS CAA record lookups in Python
Parse and filter DNS CAA records with a mock lookup function, demonstrating how certificate authorities validate domain authorization.
import dnslib
def parse_caa_record(record_string):
"""Parse a DNS CAA record string into its components."""
parts = record_string.split()
flags = int(parts[0])
tag = parts[1]
value = parts[2]
return flags, tag, value
def mock_caa_lookup(domain, caa_records):
"""Mock DNS CAA lookup that re…
How to redact secrets from log messages in Python
This code defines a logging.Filter subclass that automatically redacts sensitive keys like password, token, and API key from any dict logged.
import logging
from dataclasses import dataclass
@dataclass
class ApiResponse:
status: int
body: dict
class SecretRedactor(logging.Filter):
SENSITIVE_KEYS = {"password", "token", "secret", "api_key"}
def filter(self, record: logging.LogRecord) -> bool:
if isinstance(record.msg, dict):
…
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.