Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

24 matches
Files & data easy

Create an In-Memory SQLite Table and Query It in Python

This code creates an in-memory SQLite database, defines an employees table, inserts sample rows, and runs a filtered query with sorted results.

sqlite in-memory database
Python
import sqlite3

conn = sqlite3.connect(":memory:")
cursor = conn.cursor()

cursor.execute("""
    CREATE TABLE employees (
        id INTEGER PRIMARY KEY,
        name TEXT NOT NULL,
        department TEXT NOT NULL,
        salary REAL
    )
""")

employees = [
    (1, "Alice", "Engineering", 95000),
    (2, "Bob", "…
11 0 Open
Files & data easy

Export SQLite Query Results to CSV in Python

Connects to a SQLite database, runs a query, and writes the result rows and column headers to a CSV file using the standard library.

sqlite csv export
Python
import sqlite3
import csv

def export_query_to_csv(db_path, query, csv_path):
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    cursor.execute(query)

    rows = cursor.fetchall()
    column_names = [description[0] for description in cursor.description]

    with open(csv_path, 'w', newline='', encodi…
17 0 Open
Files & data easy

How to Bulk Insert Rows into SQLite in Python

Insert many rows into an SQLite table in one call with cursor.executemany, then verify them with a SELECT query.

sqlite bulk-insert database
Python
import sqlite3

# Create an in-memory database and a table
conn = sqlite3.connect(":memory:")
cursor = conn.cursor()
cursor.execute("CREATE TABLE products (name TEXT, price REAL, quantity INTEGER)")

# Data to insert in bulk
products = [
    ("Laptop", 999.99, 5),
    ("Mouse", 19.99, 50),
    ("Keyboard", 49.99, 30),…
13 0 Open
Files & data easy

Parameterize SQL queries in Python to prevent SQL injection

Safely fetch users from a SQLite database using parameterized queries to prevent SQL injection attacks.

sqlite3 sql injection parameterized query
Python
import sqlite3

def get_users_by_name(name):
    """Fetch users safely using parameterized query."""
    conn = sqlite3.connect(':memory:')
    cursor = conn.cursor()
    
    # Create sample table and data
    cursor.execute('CREATE TABLE users (id INTEGER, name TEXT)')
    cursor.executemany('INSERT INTO users (name…
15 0 Open
Files & data easy

Read SQLite database with sqlite3 module in Python

Connect to a SQLite database and query rows with the standard library sqlite3 module, returning results as dictionaries.

sqlite database stdlib
Python
import sqlite3
from pathlib import Path

# Create an in-memory database and a sample table
connection = sqlite3.connect(":memory:")
cursor = connection.cursor()

cursor.execute("""
CREATE TABLE employees (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    department TEXT NOT NULL,
    salary REAL
)
""")

# Inser…
17 0 Open
Dictionaries & sets easy

How to Parse Query String to Dict with Duplicate Keys in Python

Convert a URL query string into a Python dictionary, merging duplicate keys into lists while keeping single values as scalars.

query-string dict url-parsing
Python
from urllib.parse import parse_qs


def parse_query_to_dict(query_string):
    parsed = parse_qs(query_string, keep_blank_values=True)
    return {key: values if len(values) > 1 else values[0] for key, values in parsed.items()}


if __name__ == "__main__":
    query = "name=John&name=Jane&age=30&city=&city=Paris&empty…
12 0 Open
Dictionaries & sets easy

How to Serialize a Dictionary to a Query String in Python

Convert a Python dictionary into a URL-encoded query string using the standard library's urllib.parse.urlencode function.

urllib query-string urlencode
Python
import urllib.parse

def dict_to_query_string(params):
    """Serialize a dictionary to a URL query string."""
    return urllib.parse.urlencode(params)

if __name__ == "__main__":
    data = {
        "name": "Alice Johnson",
        "age": 30,
        "city": "New York",
        "interests": ["coding", "hiking"]
   …
13 0 Open
OOP & classes easy

Graph Class with Adjacency Dict in Python

Build an undirected graph class using a dictionary of adjacency lists with methods to add vertices, edges, remove edges, and query neighbors.

graph oop adjacency-list
Python
class Graph:
    def __init__(self):
        self.adjacency = {}

    def add_vertex(self, vertex):
        if vertex not in self.adjacency:
            self.adjacency[vertex] = []

    def add_edge(self, u, v):
        self.add_vertex(u)
        self.add_vertex(v)
        self.adjacency[u].append(v)
        self.adja…
12 0 Open
AI & LLM integration patterns easy

Cosine Similarity to Retrieve Top K Chunks in Python

Compute cosine similarity between a query vector and a list of chunk vectors, then return the indices and scores of the top k most similar chunks.

cosine-similarity retrieval embeddings
Python
import numpy as np
from numpy.linalg import norm

def cosine_similarity(vec1, vec2):
    return np.dot(vec1, vec2) / (norm(vec1) * norm(vec2))

def retrieve_top_k(query_vec, chunk_vectors, k=3):
    similarities = [cosine_similarity(query_vec, vec) for vec in chunk_vectors]
    top_indices = sorted(range(len(similarit…
15 0 Open
Cloud + Python easy

How to Mock DynamoDB with a Simple Dict Store in Python

A lightweight in-memory DynamoDB mock that stores items in a dict and supports put, get, and query-by-value operations for local testing.

dynamodb mock testing
Python
import json
from typing import Any, Dict, Optional


class MockDynamoDB:
    def __init__(self) -> None:
        self._store: Dict[str, Dict[str, Any]] = {}

    def put_item(self, table_name: str, item: Dict[str, Any]) -> None:
        key = str(item.get("id"))
        if table_name not in self._store:
            se…
14 0 Open
System design patterns medium

How to Implement CQRS with Separate Read and Write Models in Python

Implements Command Query Responsibility Segregation (CQRS) by splitting data into separate write and read models with dedicated repositories, using dataclasses for structure.

cqrs dataclasses repositories
Python
from dataclasses import dataclass, field
from typing import List, Dict, Optional


@dataclass
class OrderWriteModel:
    order_id: int
    customer: str
    items: List[str] = field(default_factory=list)

    def add_item(self, item: str) -> None:
        self.items.append(item)


@dataclass
class OrderReadModel:
    …
14 0 Open
API design & gRPC medium

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.

query-parsing url api
Python
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…
12 0 Open
API design & gRPC easy

How to Implement Pagination with Offset and Limit in Python

A mock API pagination pattern that parses page and per_page query parameters, computes offset and limit, and slices a list of items for a specific page.

api pagination query-params
Python
def paginate(items, page, per_page):
    offset = (page - 1) * per_page
    return items[offset:offset + per_page]


def parse_query_params(query_string):
    params = {}
    if query_string:
        for pair in query_string.split("&"):
            key, value = pair.split("=")
            params[key] = value
    page …
12 0 Open
API design & gRPC easy

How to Mock a GraphQL Query Type in Python

Create a lightweight mock of a GraphQL Query type to simulate repository lookups without a server.

graphql mock resolver
Python
import json

class Query:
    def __init__(self):
        self.starred_repos = [
            {"id": 1, "name": "graphql", "owner": "graphql"}
        ]

    def repository(self, name):
        if name == "graphql":
            return {"id": 1, "name": "graphql", "stargazerCount": 85000}
        return None


if __name…
14 0 Open
API design & gRPC easy

Sort Python list by query param order_by

Sort a list of dataclass objects dynamically by a field name passed as a query param, with asc/desc direction support.

sorting dataclasses api
Python
from dataclasses import dataclass


@dataclass
class Item:
    name: str
    price: int


def sort_items(items, order_by, direction="asc"):
    if order_by not in ("name", "price"):
        raise ValueError(f"Unsupported sort field: {order_by}")

    reverse = direction.lower() == "desc"
    return sorted(items, key=l…
11 0 Open
Observability & SRE easy

How to Mock Database Query Duration in Python

Simulate realistic database query durations with random jitter for testing dashboards, alerts, and SLO calculations.

observability mock metrics
Python
import random
import time


def mock_query_duration(db_name, avg_ms, jitter_ms=5, runs=3):
    """Simulate database query durations with realistic variation."""
    durations = []
    for _ in range(runs):
        # Base duration plus random jitter (can be negative)
        duration = avg_ms + random.uniform(-jitter_m…
14 0 Open
Big data & Spark medium

How to Mock a Catalyst Logical Plan in Python

Build a small Python class that mimics Spark Catalyst's logical plan tree for teaching or testing query optimizations.

apache-spark logical-plan catalyst
Python
from typing import Any, Dict, List, Optional


class CatalystLogicalPlan:
    """A minimal mock of Catalyst's logical plan for teaching purposes."""
    
    def __init__(self, node_type: str, **kwargs: Any) -> None:
        self.node_type = node_type
        self.attributes: Dict[str, Any] = kwargs
        self.child…
13 0 Open
Big data & Spark medium

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.

big-data query-optimization predicate-pushdown
Python
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…
15 0 Open
Database scaling & optimization medium

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.

sqlite indexes database
Python
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_…
13 0 Open
Database scaling & optimization medium

Cross Shard Query Scatter Gather Mock in Python

Simulate a distributed database cross-shard query using a scatter-gather pattern with a mock Python implementation.

scatter-gather sharding distributed-systems
Python
from dataclasses import dataclass
from typing import List, Dict


@dataclass
class NodeResponse:
    node_id: int
    data: Dict[str, float]


def mock_query_shard(shard_id: int, shard_data: Dict[str, float], query: str) -> NodeResponse:
    """Simulate querying a single shard, returning matches whose value > 50."""
 …
13 0 Open
Database scaling & optimization easy

Database indexing and query timing optimization in Python

Create SQLite indexes and time query performance to measure speedup for large table lookups in Python.

sqlite indexing query optimization
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…
14 0 Open
Database scaling & optimization medium

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.

sqlite indexing covering index
Python
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…
15 0 Open
Database scaling & optimization medium

How to Eager Load with JOIN to Reduce N+1 Queries in Python

Demonstrates eager loading with a SQL JOIN to reduce N+1 query patterns down to a single database call when fetching related data.

eager-loading n-plus-1 join
Python
import sqlite3


def eager_load_join_reduce(mock_db_path=":memory:"):
    """Demonstrate eager loading where joins reduce query count from N+1 to 1."""
    conn = sqlite3.connect(mock_db_path)
    cursor = conn.cursor()
    cursor.executescript(
        """
        CREATE TABLE authors (id INTEGER PRIMARY KEY, name TE…
16 0 Open
Database scaling & optimization medium

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.

sqlite query-plan optimization
Python
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…
14 0 Open

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

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. 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.