Reference library

Python Code Samples

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

34 matches
Functions & basics easy

Benchmark list append vs comprehension in Python

This micro-benchmark compares the speed of building a list with a for loop and append versus a list comprehension, using the timeit module to get precise timings.

timeit benchmark performance
Python
import timeit

# Build a list of the first 1,000,000 integers using append in a loop
def append_loop(n=1_000_000):
    result = []
    for i in range(n):
        result.append(i)
    return result

# Build the same list using a list comprehension
def comprehension(n=1_000_000):
    return [i for i in range(n)]

if __n…
13 0 Open
Functions & basics easy

Cache expensive function with lru_cache in Python

Use functools.lru_cache to memoize an expensive recursive function and show the dramatic speedup on repeated calls.

lru_cache caching decorators
Python
from functools import lru_cache
import time


@lru_cache(maxsize=128)
def expensive_operation(n):
    """Simulate an expensive Fibonacci-like calculation."""
    if n < 2:
        return n
    return expensive_operation(n - 1) + expensive_operation(n - 2)


if __name__ == "__main__":
    # First call (uncached) - take…
15 0 Open
Functions & basics easy

How to Compare Two Implementations with timeit in Python

Measure and compare the execution time of iterative vs recursive factorial functions using the timeit module.

timeit benchmark performance
Python
import timeit

def factorial_iterative(n):
    result = 1
    for i in range(2, n + 1):
        result *= i
    return result

def factorial_recursive(n):
    if n == 0:
        return 1
    return n * factorial_recursive(n - 1)

if __name__ == "__main__":
    n = 10
    iterations = 10000

    iterative_time = timeit…
13 0 Open
Functions & basics easy

Profile Python functions with cProfile

Profile a Python program with cProfile, capture the stats in memory, and print a sorted performance report.

cprofile performance profiling
Python
import cProfile
import pstats
import io


def slow_function():
    total = 0
    for i in range(100000):
        total += i ** 2
    return total


def medium_function():
    return sum(range(10000))


def fast_function():
    return sum(range(100))


def main():
    result1 = slow_function()
    result2 = medium_func…
11 0 Open
Errors & debugging easy

How to Build a Simple Debug Timer in Python

Create a context manager class to time the execution of a code block with a one-line printout.

debugging context-manager performance
Python
import time


class DebugTimer:
    """Context manager that times the execution of a code block."""

    def __init__(self, label="Operation"):
        self.label = label
        self.start_time = None

    def __enter__(self):
        self.start_time = time.perf_counter()
        return self

    def __exit__(self, e…
15 0 Open
OOP & classes easy

Slots Class: How to Reduce Memory Usage in Python

Use __slots__ to prevent dynamic attribute creation and reduce per-instance memory overhead, while keeping methods intact.

memory slots class
Python
class SlotsDemo:
    __slots__ = ("name", "age", "email")

    def __init__(self, name, age, email):
        self.name = name
        self.age = age
        self.email = email

    def describe(self):
        return f"{self.name}, {self.age}, {self.email}"

if __name__ == "__main__":
    instance = SlotsDemo("Alice", …
12 0 Open
Automation & scripting easy

Benchmark Disk Write Speed in Python with tempfile

Benchmark raw disk write performance by writing a temporary file in 1MB chunks and measuring throughput in MB/s.

benchmark tempfile performance
Python
import os
import tempfile
import time

def benchmark_write(size_mb=50):
    size_bytes = size_mb * 1024 * 1024
    chunk = b'x' * 1024 * 1024  # 1 MB chunk

    with tempfile.NamedTemporaryFile(delete=True) as tmp:
        start = time.perf_counter()
        written = 0
        while written < size_bytes:
            …
11 0 Open
Automation & scripting easy

How to generate website performance reports from HTTP requests in Python

Measure and report website load time, status code, and content size using Python's standard library.

http performance urllib
Python
import urllib.request
import time

def measure_website_load_time(url):
    """Measures total loading time of a website."""
    start_time = time.time()
    try:
        with urllib.request.urlopen(url, timeout=10) as response:
            content = response.read()
            status_code = response.status
            …
37 0 Open
Concurrency & performance easy

How to Convert Data in Parallel with ThreadPoolExecutor in Python

This example demonstrates converting a list of items in parallel using ThreadPoolExecutor, showing performance gains over serial processing.

concurrency threadpoolexecutor parallelism
Python
import time
from concurrent.futures import ThreadPoolExecutor


def convert_data(item):
    """Simulate a CPU/IO-bound conversion task."""
    time.sleep(0.05)  # simulate work
    return item.upper()


if __name__ == "__main__":
    items = [f"item_{i}" for i in range(20)]

    start = time.perf_counter()
    serial_…
15 0 Open
Concurrency & performance easy

How to Memoize Pure Functions with functools.lru_cache in Python

Use functools.lru_cache to memoize a pure Fibonacci function and avoid recomputing repeated values.

lru-cache memoization functools
Python
from functools import lru_cache


@lru_cache(maxsize=128)
def fibonacci(n: int) -> int:
    """Return the nth Fibonacci number (0-indexed) using memoization."""
    if n < 2:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)


if __name__ == "__main__":
    for i in range(10):
        print(f"fibonacci({…
15 0 Open
Concurrency & performance easy

How to Time Code Performance with timeit in Python

Benchmark two implementations of the same logic using Python's timeit module and compare their execution speeds.

timeit performance benchmark
Python
import timeit

# Implementation 1: Using a list comprehension
def list_comprehension_squares(n):
    return [i ** 2 for i in range(n)]

# Implementation 2: Using a for loop with append
def loop_squares(n):
    result = []
    for i in range(n):
        result.append(i ** 2)
    return result

if __name__ == "__main__"…
12 0 Open
Concurrency & performance easy

How to Use Array Typecodes for Compact Numeric Storage in Python

This code demonstrates how to use the `array` module with typecodes to store integers, floats, and bytes in a memory-efficient way compared to standard Python lists.

array memory performance
Python
from array import array

def demonstrate_array_types():
    # Compact integer arrays
    small_ints = array('i', [1, 2, 3, 4, 5])
    unsigned_ints = array('I', [10, 20, 30])
    
    # Floating point arrays
    floats = array('f', [1.5, 2.5, 3.5])
    doubles = array('d', [1.123456789, 2.987654321])
    
    # Charac…
15 0 Open
Concurrency & performance easy

How to Use ThreadPoolExecutor and ProcessPoolExecutor in Python

Compares ThreadPoolExecutor and ProcessPoolExecutor by running CPU-bound and I/O-tolerant tasks over a large list, printing elapsed times and first results.

concurrency threadpool processpool
Python
import time
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
import math

numbers = list(range(1, 1000001))


def compute_square(n):
    return n * n


def compute_sqrt(n):
    return math.sqrt(n)


def run_executor(executor, func, data):
    start = time.perf_counter()
    results = list(executo…
15 0 Open
Concurrency & performance easy

How to Use bisect.insort in Python to Maintain a Sorted List

Insert items into an already sorted list using Python's bisect.insort to keep it sorted efficiently in O(n) time.

bisect sorted insertion
Python
import bisect

def maintain_sorted_list():
    data = [3, 1, 4, 1, 5, 9, 2, 6]
    sorted_list = []
    
    for num in data:
        bisect.insort(sorted_list, num)
    
    print("Original data:", data)
    print("Sorted list maintained with insort:", sorted_list)
    
    # Insert new values to maintain sorted orde…
13 0 Open
Concurrency & performance easy

How to Use functools.cache for Unbounded Memoization in Python

Speed up repeated recursive calls by memoizing function results with Python's built-in functools.cache decorator.

functools memoization performance
Python
```python
import functools
import time


@functools.cache
def fib(n):
    if n < 2:
        return n
    return fib(n - 1) + fib(n - 2)


if __name__ == "__main__":
    start = time.perf_counter()
    result = fib(30)
    elapsed = time.perf_counter() - start

    print(f"fib(30) = {result}")
    print(f"computed in {…
14 0 Open
Concurrency & performance easy

How to Use pool.map for CPU-Bound Tasks in Python

Distribute CPU-intensive functions across processes with multiprocessing.Pool.map and measure the performance gain.

multiprocessing pool cpu-bound
Python
from multiprocessing import Pool
import time

def cpu_bound_task(n):
    """Mock CPU-bound work: compute sum of squares."""
    total = 0
    for i in range(n):
        total += i * i
    return total

if __name__ == "__main__":
    numbers = [10_000_000, 12_000_000, 8_000_000, 15_000_000]

    start = time.perf_count…
11 0 Open
Concurrency & performance easy

How to Use uvloop Faster Event Loop

Install uvloop at startup to replace asyncio's default event loop with a faster libuv-based one, with a graceful fallback when it's unavailable.

uvloop asyncio event-loop
Python
import asyncio
try:
    import uvloop
    uvloop.install()
    USING_UVLOOP = True
except ImportError:
    USING_UVLOOP = False


async def fetch_data(index):
    await asyncio.sleep(0.01)
    return f"data-{index}"


async def main():
    tasks = [fetch_data(i) for i in range(10)]
    results = await asyncio.gather(*…
14 0 Open
Concurrency & performance easy

How to Vectorize a Function with a Pure Python Fallback

Create a decorator that calls a scalar function directly for a single value and routes list inputs to a pure-Python fallback for vectorized processing without NumPy.

vectorization decorator fallback
Python
import math


def fallback_vectorize(func, fallback=None):
    """Vectorize a scalar function with a pure-Python fallback for lists."""
    if fallback is None:
        fallback = lambda x: [func(i) for i in x]

    def wrapped(*args):
        if len(args) == 1 and isinstance(args[0], (list, tuple)):
            retur…
14 0 Open
Concurrency & performance easy

How to use ThreadPoolExecutor for concurrent tasks in Python

Run blocking functions in parallel with ThreadPoolExecutor and as_completed, cutting total runtime from 5 sequential sleeps to about 1 second.

concurrency threadpoolexecutor parallel
Python
import time
from concurrent.futures import ThreadPoolExecutor, as_completed


def fetch_data(item):
    """Simulate a slow operation with a fixed delay."""
    time.sleep(0.2)
    return item * 2


def main():
    items = [1, 2, 3, 4, 5]
    start = time.perf_counter()

    with ThreadPoolExecutor(max_workers=3) as ex…
14 0 Open
Testing & modern typing easy

How to Write a Fast Smoke Test for a Critical Path in Python

A quick smoke test that validates the /health critical path executes fast enough, raising errors on wrong paths or slow responses.

smoke-test performance health-check
Python
import time

def smoke_test(path):
    if path != "/health":
        raise ValueError("Critical path expected /health")
    start = time.perf_counter()
    # Simulate the critical health check work
    time.sleep(0.01)
    elapsed = time.perf_counter() - start
    if elapsed > 0.05:
        raise RuntimeError("Health …
12 0 Open
Caching & Redis easy

Cache Asides in Python with a Read-Through Loader

Implements a cache-aside pattern with a read-through loader that fetches missing keys from a backing data store and caches them.

caching cache-aside read-through
Python
class DataStore:
    """Mock database with a few records."""
    def __init__(self):
        self.data = {1: "Alice", 2: "Bob", 3: "Charlie"}

    def get(self, key):
        print(f"Loading key {key} from database")
        return self.data.get(key)


class CacheAsideLoader:
    """Cache-aside pattern with a read-thr…
15 0 Open
Caching & Redis easy

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.

redis caching filtering
Python
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…
13 0 Open
Caching & Redis easy

How to memoize a function in Python with lru_cache

Use functools.lru_cache to memoize a recursive Fibonacci function, caching results for a fixed number of calls to avoid repeated computation.

lru_cache memoization functools
Python
from functools import lru_cache

@lru_cache(maxsize=128)
def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)

if __name__ == "__main__":
    for i in range(10):
        print(f"fib({i}) = {fibonacci(i)}")
    print(f"Cache info: {fibonacci.cache_info()}")
13 0 Open
Observability & SRE easy

Generate Mock CPU and Memory Metrics in Python

Build a mock_host_metrics() generator that outputs realistic CPU and memory usage percentages for monitoring demos and tests.

mock metrics monitoring
Python
import time
import random


def mock_host_metrics():
    """Generate mock CPU and memory metrics for a host."""
    cpu_percent = round(random.uniform(10.0, 95.0), 1)
    memory_percent = round(random.uniform(20.0, 90.0), 1)
    memory_used_mb = round(random.uniform(512, 8192), 1)

    return {
        "timestamp": in…
15 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.