Reference library

Python Code Samples

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

13 matches
Functions & basics medium

How to Create a Counter Closure in Python

Build a closure in Python that remembers and increments a counter across calls without using global variables.

closures nonlocal state
Python
def create_counter(start=0):
    count = start
    def increment():
        nonlocal count
        count += 1
        return count
    return increment

if __name__ == "__main__":
    counter = create_counter(10)
    print(counter())
    print(counter())
    print(counter())
12 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
Git + Python medium

How to Make a Git Commit Heatmap by Hour in Python

Parse a git log output and count commits by weekday and hour, then print a compact heatmap table.

git logging datetime
Python
import re
from collections import Counter
from datetime import datetime

def parse_commits(log_text):
    """Parse git log lines and count commits by (weekday, hour)."""
    pattern = re.compile(r"^Date:\s+(.+)$")
    counts = Counter()
    
    for line in log_text.splitlines():
        match = pattern.match(line)
  …
13 0 Open
Concurrency & performance medium

How to Use ThreadPoolExecutor for Concurrent Tasks in Python

Compare sequential execution with ThreadPoolExecutor for I/O-bound tasks, measuring speedup and timing with perf_counter.

concurrency threadpool performance
Python
import time
import threading
from concurrent.futures import ThreadPoolExecutor


def fetch_data(index):
    """Simulate a synchronous data fetch."""
    time.sleep(0.1)
    return f"data-{index}"


def run_sequential(total=10):
    """Run tasks one after another."""
    start = time.perf_counter()
    results = [fetch…
14 0 Open
Concurrency & performance medium

How to Use asyncio Lock to Protect a Shared Counter in Python

This code demonstrates how to use an asyncio.Lock to safely increment a shared counter from multiple concurrent coroutines.

asyncio lock concurrency
Python
import asyncio

async def increment(counter, lock, increments):
    for _ in range(increments):
        async with lock:
            counter[0] += 1

async def main():
    counter = [0]
    lock = asyncio.Lock()
    tasks = [
        increment(counter, lock, 1000)
        for _ in range(5)
    ]
    await asyncio.gath…
16 0 Open
Testing & modern typing medium

How to Compare Execution Speed Between Python Functions

Measure and compare the average execution time of multiple Python functions using a reusable benchmark helper with time.perf_counter.

performance benchmarking time
Python
import time
import random

def method_a(values):
    """Sort using built-in sorted."""
    return sorted(values)

def method_b(values):
    """Sort using list's sort method."""
    values_copy = values[:]
    values_copy.sort()
    return values_copy

def method_c(values):
    """Sort manually using bubble sort (slow,…
37 0 Open
Caching & Redis medium

Refresh Proactive TTL Renewal in Python

This snippet implements a proactive TTL renewal pattern that refreshes a cache expiration before it lapses, using a mock counter to track renewals.

caching ttl renewal
Python
import time
from datetime import datetime, timezone

class TTLRenewer:
    def __init__(self, ttl_seconds=10, renew_at=0.5):
        self.ttl = ttl_seconds
        self.last_renewed = time.time()
        self.renew_threshold = ttl_seconds * renew_at
        self.renewals = 0

    def check_and_renew(self):
        if …
13 0 Open
Reliability & rate limiting medium

How to implement a rate-limited shared counter in Python

Implements a thread-safe global counter that allows a maximum number of increments per second using a lock and time-based refill.

rate-limiting threading global-counter
Python
import threading
import time
import random

counter = 0
lock = threading.Lock()
MAX_CALLS_PER_SECOND = 3
last_refill = time.time()

def rate_limited_increment():
    global counter, last_refill
    with lock:
        now = time.time()
        if now - last_refill >= 1.0:
            last_refill = now
            count…
12 0 Open
Big data & Spark medium

Accumulators Global Counter Mock in Python

Shows an accumulator-style global counter with a mock patch to control its value in tests.

accumulator global state mock
Python
import unittest
from unittest.mock import patch

# Module-level global counter accumulator
counter = 0

def increment(by=1):
    """Increment the global counter in place (accumulator pattern)."""
    global counter
    counter += by
    return counter

def reset():
    """Reset the counter to zero."""
    global count…
14 0 Open
Big data & Spark medium

Approximate Distinct Count in Python with HyperLogLog

Mock a large data stream and estimate the number of distinct items with a HyperLogLog-style probabilistic counter to save memory.

hyperloglog distinct-count probabilistic
Python
import random
import string
from collections import Counter
import math

class ApproxCountDistinct:
    def __init__(self, num_buckets=16):
        self.num_buckets = num_buckets
        self.max_zeros = [0] * num_buckets
        
    def _hash(self, item):
        # Simple string hash to a 32-bit integer
        h = …
14 0 Open
Big data & Spark medium

How to Mock a UDAF Aggregate Function in Python

This code provides a minimal mock of a User-Defined Aggregate Function (UDAF), simulating the initialize-update-merge-finalize lifecycle with a defaultdict counter.

udaf aggregate mock
Python
from collections import defaultdict

class MockUDAF:
    """A minimal mock of a User-Defined Aggregate Function.

    Simulates aggregate lifecycle: initialize, update per row,
    and finalize the result.
    """

    def __init__(self):
        self._buffer = defaultdict(int)

    def initialize(self):
        """Re…
13 0 Open
A/B testing & experimentation medium

How to Mock Mutual Exclusion for A/B Experiment Groups in Python

Simulate mutual exclusion for experiment groups using a thread-safe lock, ensuring only one member updates the shared counter at a time.

threading mutual-exclusion ab-testing
Python
import threading
import time
import random


class CountingGate:
    """A mock mutual exclusion gate using a lock."""
    def __init__(self):
        self.counter = 0
        self.lock = threading.Lock()

    def enter(self, group_id, member_id):
        with self.lock:
            current = self.counter
            t…
13 0 Open
A/B testing & experimentation medium

Synthetic Control in Python: Mock Example

Implements synthetic control from scratch: learns donor weights via ridge regression on pre-period data, then predicts a counterfactual for the treated unit.

synthetic-control causal-inference numpy
Python
import numpy as np

class SyntheticControl:
    def __init__(self, data, treated_index, pre_periods, post_periods):
        self.data = np.array(data, dtype=float)
        self.treated_index = treated_index
        self.pre_periods = pre_periods
        self.post_periods = post_periods
        
    def fit_weights(sel…
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.