Reference library

Python Code Samples

Medium snippets you can copy, study, and run in the browser editor.

23 matches
Errors & debugging medium

How to Diff Two Dicts in Python for Config Drift

Recursively compare two dictionaries and report added, removed, and changed keys with their old and new values for debugging configuration drift.

dict diff config
Python
def diff_dicts(a, b, path=""):
    differences = []

    for key in a.keys() | b.keys():
        new_path = f"{path}.{key}" if path else key

        if key not in a:
            differences.append((new_path, "<missing>", b[key], "added"))
        elif key not in b:
            differences.append((new_path, a[key], "<…
12 0 Open
Files & data medium

How to Audit Environment Variable Files for Missing Values in Python

A Python tool that reads an environment variable file and reports any variables with empty or missing values.

environment-variables file-audit configuration
Python
import os
import re
from pathlib import Path

def audit_env_file(filepath: str) -> None:
    """
    Audit an environment variable file for missing values.
    Prints file status and lists variables that have empty values.
    """
    path = Path(filepath)
    if not path.exists():
        print(f"Error: File '{filepa…
40 0 Open
Files & data medium

Read Parquet-Like Columnar CSV Chunks in Python

A Python generator that reads a CSV file column-by-column, yielding dictionary chunks where each key points to a list of values—mirroring how Parquet stores data columnar.

csv columnar generator
Python
```python
import csv
from pathlib import Path
from typing import Iterator, List

def read_parquet_like_columnar(csv_path: str, column_names: List[str], chunk_size: int = 2) -> Iterator[dict]:
    """Read CSV data in columnar chunks, similar to how parquet stores columns."""
    csv_file = Path(csv_path)
    with csv_f…
13 0 Open
Dictionaries & sets medium

Get Nested Dict Value with Default in Python

Access values deep inside a nested dictionary using a dotted path string, returning a default when any key is missing.

dictionaries nested default-value
Python
def get_nested(d, path, default=None):
    """Walk a nested dict along a dotted path, returning default if missing."""
    current = d
    for key in path.split("."):
        if isinstance(current, dict) and key in current:
            current = current[key]
        else:
            return default
    return current
…
16 0 Open
Dictionaries & sets medium

How to Deep Merge Nested Dicts Recursively in Python

Recursively merge two Python dictionaries, with overlay values taking precedence while preserving nested structures.

dict-merge recursion nested-dicts
Python
def deep_merge(base, overlay):
    """
    Recursively merge two dictionaries.
    Values in 'overlay' take precedence over 'base'.
    """
    result = base.copy()
    
    for key, value in overlay.items():
        if key in result and isinstance(result[key], dict) and isinstance(value, dict):
            result[key…
14 0 Open
Dictionaries & sets medium

How to Recursively Remove None Values from Nested Dictionaries in Python

Recursively removes all None values from nested dictionaries and lists while preserving non-None data.

dictionaries recursion data-cleaning
Python
def prune_none(obj):
    if isinstance(obj, dict):
        return {
            k: prune_none(v)
            for k, v in obj.items()
            if v is not None and prune_none(v) is not None
        }
    elif isinstance(obj, list):
        pruned = [prune_none(item) for item in obj]
        pruned = [item for item i…
15 0 Open
Algorithms & data structures medium

Find Missing Numbers, Duplicates, and Ranges in Python

Analyze a list to identify missing numbers, duplicate values, and contiguous ranges using sets and the Counter class.

algorithms sets counting
Python
def find_missing_duplicates_ranges(numbers):
    """Find missing numbers, duplicates, and ranges in a list."""
    from collections import Counter
    
    if not numbers:
        return {"missing": [], "duplicates": [], "ranges": []}
    
    full_range = set(range(min(numbers), max(numbers) + 1))
    present = set(n…
12 0 Open
Algorithms & data structures medium

Find the Duplicate Number in Python Using Floyd's Cycle Detection

Detects the duplicate integer in an array of n+1 numbers (values 1 to n) in O(n) time and O(1) space using Floyd's cycle detection algorithm applied to a linked-list model.

floyd-cycle duplicate-number two-pointers
Python
def find_duplicate(nums):
    slow = nums[0]
    fast = nums[0]
    
    # Phase 1: Find intersection point of the cycle
    while True:
        slow = nums[slow]
        fast = nums[nums[fast]]
        if slow == fast:
            break
    
    # Phase 2: Find the start of the cycle (the duplicate)
    slow = nums[0…
14 0 Open
Algorithms & data structures medium

Implement Insert Delete GetRandom O(1) in Python

Build a RandomizedSet class that supports insert, delete, and get_random in average O(1) time using a list and a dictionary mapping values to indices.

randomized-set o1-lookup hash-map
Python
import random

class RandomizedSet:
    def __init__(self):
        self.values = []
        self.index_map = {}

    def insert(self, val):
        if val in self.index_map:
            return False
        self.index_map[val] = len(self.values)
        self.values.append(val)
        return True

    def delete(self…
12 0 Open
Comprehensions & generators medium

How to Send Values into a Python Generator Coroutine

Use the .send() method to pass values into a running generator coroutine and capture them.

generators coroutines yield
Python
def coroutine():
    received = []
    while True:
        value = yield
        received.append(value)
        print(f"Coroutine received: {value}")
        if value == "stop":
            break
    return received

if __name__ == "__main__":
    gen = coroutine()
    next(gen)  # Prime the generator
    gen.send("he…
13 0 Open
Comprehensions & generators medium

Merge Sorted Iterators with a Heap Generator in Python

Merge multiple sorted iterators into a single sorted stream using a heap and generator, yielding values lazily in order.

heapq generator merge
Python
import heapq

def merge_sorted_iterators(*iterators):
    heap = []
    for idx, iterator in enumerate(iterators):
        try:
            value = next(iterator)
            heapq.heappush(heap, (value, idx, iterator))
        except StopIteration:
            continue

    while heap:
        value, idx, iterator = …
15 0 Open
Data pipelines & processing medium

How to Find Missing Values in Large Datasets in Python

Analyze missing values across multiple large pandas DataFrames with counts and percentages.

pandas missing-data data-cleaning
Python
import pandas as pd
import numpy as np

def find_missing_values_summary(datasets):
    """Analyze missing values across multiple datasets (dict of name: DataFrame)."""
    summary = {}
    for name, df in datasets.items():
        missing_count = df.isnull().sum()
        total_rows = len(df)
        missing_pct = (mi…
41 0 Open
Data pipelines & processing medium

Pivot long to wide transformation dict

Transform a list of dictionaries from long format to wide format by pivoting on a key column and aggregating values, using pure Python.

pivot transformation data-cleaning
Python
def pivot_long_to_wide(rows, key_col, value_col, id_cols=None):
    """
    Convert long-format data (list of dicts) to wide format.
    
    Args:
        rows: List of dicts in long format
        key_col: Column name to pivot on (becomes new column headers)
        value_col: Column name whose values become the cel…
11 0 Open
Cloud + Python medium

How to Mock Azure Key Vault Secret Get in Python

Mock an Azure Key Vault client's get_secret method with unittest.mock to test functions that retrieve secret values without hitting the real service.

azure key-vault unittest
Python
import unittest
from unittest.mock import MagicMock, patch


def get_secret(key_vault_client, secret_name):
    """Retrieve a secret value from an Azure Key Vault client."""
    secret = key_vault_client.get_secret(secret_name)
    return secret.value


class TestKeyVaultSecretGet(unittest.TestCase):
    def test_get_…
13 0 Open
Concurrency & performance medium

How to Use threading.local for Per-Thread Data in Python

Use threading.local to keep thread-specific data — each thread gets its own copy of the attribute, so values don't leak between threads.

threading thread-local concurrency
Python
import threading
import time

local_storage = threading.local()

def worker(name):
    local_storage.name = name
    time.sleep(0.1)
    print(f"Thread {threading.current_thread().name}: {local_storage.name}")

if __name__ == "__main__":
    threads = []
    for i in range(3):
        t = threading.Thread(target=worke…
14 0 Open
Testing & modern typing medium

How to Validate Data in Python with Typing Hints

Build a runtime validation helper that checks values against Python type hints like Optional, list, and basic types.

typing validation type-hints
Python
from typing import Any, Optional, Union, TypeVar, get_origin, get_args

T = TypeVar("T")

def validate(value: Any, expected_type: type) -> Optional[str]:
    """Returns an error message if value doesn't match expected_type, else None."""
    # Handle Optional[...] types
    origin = get_origin(expected_type)
    if or…
14 0 Open
API design & gRPC medium

How to Validate Request Body JSON Against a Schema in Python

Build a lightweight schema validator to check required fields, types, string lengths, allowed values, and nested objects in a JSON request body.

api-validation json schema-validation
Python
import json


def validate_against_schema(data, schema, path=""):
    errors = []

    if not isinstance(data, dict):
        errors.append(f"{path}: expected object, got {type(data).__name__}")
        return errors

    for field, rules in schema.items():
        field_path = f"{path}.{field}" if path else field

  …
15 0 Open
Streaming & messaging medium

How to Aggregate Periodic Snapshot Data in Python

Generates mock snapshot data and groups values into periods to compute average aggregates with Python's standard library.

aggregation snapshots streaming
Python
import random
from collections import defaultdict

def snapshot_aggregate(n=10, period=3):
    data = defaultdict(list)
    for i in range(n):
        key = f"item_{i % period}"
        data[key].append(random.randint(1, 100))
    return dict(data)

def aggregate_periodic(snapshots, period=3):
    result = {}
    for …
14 0 Open
Caching & Redis medium

How to Implement a Write-Through Cache in Python with a Mock Database

A thread-safe write-through cache that updates both cache and mock database atomically, computing values only after a successful write to the database.

caching write-through threading
Python
import threading
import time
import random


class WriteThroughCache:
    def __init__(self):
        self.cache = {}
        self.db = {}
        self.lock = threading.Lock()

    def write(self, key, value):
        with self.lock:
            # Simulate slow database write
            time.sleep(random.uniform(0.01…
12 0 Open
Caching & Redis medium

How to Mock zlib Compression for Cache Values in Python

Compress cache values with zlib and mock the compress function in unit tests to simulate cache behavior.

zlib mock caching
Python
import zlib
from unittest.mock import patch

def compress_value(data: bytes) -> bytes:
    """Compress data using zlib and return the compressed bytes."""
    return zlib.compress(data)

def decompress_value(compressed: bytes) -> bytes:
    """Decompress zlib data and return the original bytes."""
    return zlib.deco…
11 0 Open
Caching & Redis medium

How to Serialize Cache Values with JSON and Pickle in Python

Serialize cache values using JSON for simple types or pickle for arbitrary objects, with robust error handling for unsupported types like mocks.

serialization caching json
Python
import json
import pickle
from unittest.mock import Mock

def serialize(value, method="json"):
    """Serialize a cache value using JSON or pickle with type checking."""
    if method == "json":
        try:
            return json.dumps(value).encode("utf-8")
        except TypeError as e:
            raise ValueErro…
11 0 Open
Caching & Redis medium

Implement a TTL cache with a mock clock in Python

This code creates a simple TTL cache that stores values with an expiration timestamp and allows injecting a mock time function to test expiry behavior deterministically.

cache ttl mocking
Python
import time
from functools import wraps

class TTLCache:
    def __init__(self, ttl_seconds):
        self.ttl = ttl_seconds
        self.cache = {}
        self._now = time.time

    def set_mock_time(self, mock_time_fn):
        """Inject a mock time function for testing TTL expiry."""
        self._now = mock_time_…
15 0 Open
Observability & SRE medium

Summary Quantile Mock Sketch in Python

Build a memory-efficient sketch that stores sorted bins of data points to answer approximate quantile queries like median without keeping all values in memory.

quantile sketch statistics
Python
import random
import statistics
from collections import Counter

class SummaryQuantileSketch:
    """
    A simple sketch that stores a fixed-size summary of data (min, max, deciles)
    using sorted bins, then answers approximate quantile queries.
    """
    def __init__(self, bins=10):
        self.bins = bins
    …
13 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.