Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
Create a Local Search Engine to Instantly Find Files on Your Computer in Python
Build a local file search engine in Python that indexes files by name, extension, and glob pattern for instant retrieval.
import os
import sys
import time
from pathlib import Path
import fnmatch
class LocalSearchEngine:
def __init__(self, root_directory="."):
self.root_directory = Path(root_directory)
self.file_index = {}
def build_index(self):
"""Build a complete index of files in the root direc…
How to shard output by primary key hash mod N in Python
This code computes a consistent shard index for any primary key string using an MD5 hash mod the number of shards, enabling stable key-based data distribution.
import hashlib
def shard_id(primary_key: str, num_shards: int) -> int:
"""Return the shard index for a primary key using MD5 hash mod N."""
digest = hashlib.md5(primary_key.encode("utf-8")).hexdigest()
hash_int = int(digest, 16)
return hash_int % num_shards
if __name__ == "__main__":
keys = ["use…
How to Mock CloudFront Invalidation Paths in Python
Build a sorted, deduplicated list of CloudFront invalidation paths from a set of file paths, adding implicit index.html entries.
import argparse
def build_invalidation_paths(files, include_index=True):
"""
Create CloudFront invalidation paths from a list of files.
Converts file names to root-relative paths and optionally adds /index.html.
"""
paths = []
for f in files:
f = f.strip()
if not f:
…
How to Build an Append-Only Event Store in Python
Implement a simple append-only event store class that stores events in a list and supports retrieval by index range.
class EventStore:
def __init__(self):
self._events = []
def append(self, event):
"""Append an event to the store."""
self._events.append(event)
def get_events(self, start=0, end=None):
"""Return events from start index to end (exclusive)."""
return self._events[sta…
Partition Data by Hash Key Mod N in Python
Returns a partition index for a string key by hashing it with MD5 and taking modulo N, then groups sample keys into partitions.
import hashlib
def partition_key(key: str, num_partitions: int) -> int:
"""Return partition index for key using MD5 hash mod N."""
digest = hashlib.md5(key.encode()).hexdigest()
return int(digest, 16) % num_partitions
if __name__ == "__main__":
keys = ["alice", "bob", "carol", "dave", "eve"]
nu…
How to Detect Data Drift with PSI in Python
Calculate the Population Stability Index (PSI) in Python to compare expected vs actual distributions and detect data drift in machine learning pipelines.
import numpy as np
def calculate_psi(expected, actual, buckets=10):
"""Calculate Population Stability Index (PSI) between two distributions."""
# Create bucket edges based on expected distribution percentiles
edges = np.percentile(expected, np.linspace(0, 100, buckets + 1))
edges[-1] = np.inf # Ensur…
B-Tree Insert and In-Order Traversal in Python
Simulates a B-tree (order 2) with insert and split logic, then prints keys in sorted order via in-order traversal.
class BTreeNode:
def __init__(self, leaf=False):
self.leaf = leaf
self.keys = []
self.children = []
def is_full(self, t):
return len(self.keys) == 2 * t - 1
class BTree:
def __init__(self, t=2):
self.t = t
self.root = BTreeNode(leaf=True)
def insert(s…
Build a Full Text Search Index in Python
Create a simple inverted index for full-text search with the standard library, supporting multi-word AND queries across documents.
import re
from collections import defaultdict
class SimpleTextIndex:
def __init__(self):
self.index = defaultdict(list)
self.documents = {}
def add_document(self, doc_id, text):
self.documents[doc_id] = text
words = set(re.findall(r'\w+', text.lower()))
for word in wo…
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…
Composite index leftmost prefix in Python
Simulate a composite index in SQLite and check whether query columns match the leftmost prefix rule for index usage.
import sqlite3
def get_indexed_columns(table_name):
"""Simulate a composite index by reading column names that start with 'idx_'."""
conn = sqlite3.connect(":memory:")
conn.execute(f"CREATE TABLE {table_name} (id INTEGER, idx_col1 TEXT, idx_col2 INTEGER, other TEXT)")
conn.execute(f"CREATE INDEX idx_…
Database Helper in Python with SQLite Scaling Optimization
Build a beginner-friendly SQLite database helper class with WAL, indexed queries, and efficient batch inserts for scaling.
import sqlite3
from contextlib import contextmanager
class DatabaseHelper:
"""Beginner-friendly helper for SQLite database operations with scaling tips."""
def __init__(self, db_path):
self.db_path = db_path
@contextmanager
def connection(self):
"""Context manager for automatic comm…
Database indexing and query timing optimization in Python
Create SQLite indexes and time query performance to measure speedup for large table lookups in Python.
import sqlite3
import time
def time_query(db_path, query, params=()):
conn = sqlite3.connect(db_path)
conn.execute("PRAGMA journal_mode = WAL")
start = time.perf_counter()
result = conn.execute(query, params).fetchall()
elapsed = time.perf_counter() - start
conn.close()
return result, ela…
Hash index equality mock concept in Python
A simple hash index class in Python that stores key-value pairs in buckets and demonstrates basic equality-based lookup.
class HashIndex:
def __init__(self):
self._buckets = {}
def insert(self, key, value):
"""Insert a key-value pair into the hash index."""
index = hash(key) % 10
if index not in self._buckets:
self._buckets[index] = []
self._buckets[index].append((key, value))…
How to Create a Covering Index with INCLUDE Columns in Python
Create a covering index with INCLUDE columns in SQLite from Python and inspect the query plan to confirm the index covers the query.
import sqlite3
def create_covering_index_mock():
conn = sqlite3.connect(":memory:")
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT,
department TEXT,
salary INTEGER
)
""")
employe…
How to Create a Database Helper Class for Beginners in Python
Build a beginner-friendly SQLite helper class with indexing and batch inserts to optimize database queries in Python.
import sqlite3
class DatabaseHelper:
def __init__(self, db_path):
self.connection = sqlite3.connect(db_path)
self.cursor = self.connection.cursor()
def create_table_with_index(self, table_name, columns, indexed_column):
columns_sql = ", ".join(f"{name} {dtype}" for name, dtype in col…
How to Explain SQLite Query Plans in Python
Build a Python function that runs EXPLAIN QUERY PLAN on SQLite in-memory tables and prints the optimizer's execution plan for any SELECT statement.
import sqlite3
def explain_query(sql: str) -> str:
"""Return the SQLite query plan for the given SQL statement."""
conn = sqlite3.connect(":memory:")
cursor = conn.cursor()
# Create sample data for a realistic plan
cursor.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)")
c…
How to Optimize SQLite Database Performance in Python
A Python helper that creates an index, enables WAL mode, and tunes synchronous settings to optimize SQLite database performance.
import sqlite3
DATABASE_PATH = "beginners.db"
UNOPTIMIZED_TABLE_SCHEMA = """
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
email TEXT NOT NULL
)
"""
def optimize_database(db_path: str = DATABASE_PATH) -> dict:
with sqlite3.connect(db_path) as connection:
curs…
How to Shard Data by User ID Hash in Python
Deterministically map user IDs to shard indexes using an MD5 hash modulo the shard count in Python.
import hashlib
def shard_id(user_id: str, num_shards: int = 4) -> int:
"""Deterministically map a user_id to a shard index using MD5."""
digest = hashlib.md5(user_id.encode("utf-8")).hexdigest()
return int(digest[:8], 16) % num_shards
if __name__ == "__main__":
user_ids = ["alice", "bob", "carol", "d…
How to Speed Up Column Lookups with DataFrame Index in Python
Use pandas set_index to make repeated column value lookups O(1)-style fast instead of scanning the whole DataFrame each time.
import pandas as pd
# Mock dataset with duplicate customer IDs
data = {"customer_id": [101, 102, 103, 101, 104, 102],
"order_amount": [250.0, 85.5, 300.0, 175.25, 420.0, 95.75]}
df = pd.DataFrame(data)
df = df.set_index("customer_id")
# Simulated lookup request
search_id = 102
# Fast index-based lookup (no…
How to enforce a unique index constraint in Python
Mock a database unique index in Python that rejects duplicate rows based on one or more columns.
class MockIndex:
def __init__(self, columns):
self.columns = columns
self._values = set()
def insert(self, row):
key = tuple(row[col] for col in self.columns)
if key in self._values:
raise ValueError(f"Duplicate key {key} for columns {self.columns}")
self._v…
Monitor Database Index Bloat in Python
Simulates index bloat checks for database tables using random ratio thresholds and reports alerts per index.
import random
import time
class IndexBloatMonitor:
def __init__(self, thresholds=(0.5, 0.8, 0.9)):
self.thresholds = thresholds
self.indices = {
"users_pk": 48.2,
"orders_created_idx": 124.7,
"products_name_idx": 15.3,
"payments_user_idx": 203.9,
…
Simulate a GIN Index for JSONB in Python
Build a mock Generalized Inverted Index (GIN) that flattens JSON documents into key-value tokens for fast lookup queries, mimicking PostgreSQL JSONB indexing.
import json
import random
from collections import defaultdict
# Mock GIN (Generalized Inverted Index) for JSONB key-value pairs
class GINIndex:
def __init__(self):
self.posting_lists = defaultdict(list) # token -> list of doc_ids
def index(self, doc_id, json_obj):
"""Index a JSON documen…
Snowflake ID Generator with Cluster Index Mock in Python
A thread-safe Snowflake ID generator mock that creates unique 64-bit IDs across simulated cluster nodes and maintains a sorted in-memory index for range queries.
import time
import threading
class SnowflakeIDGenerator:
def __init__(self, machine_id, datacenter_id):
self.machine_id = machine_id
self.datacenter_id = datacenter_id
self.sequence = 0
self.last_timestamp = -1
self.machine_bits = 5
self.datacenter_bits = 5
…
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.