Reference library

Python Code Samples

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

68 matches
Comprehensions & generators easy

How to Lazily Transform Items in Python with a Generator

Map a transform function over an iterable lazily with a generator so items are processed on demand, not up front.

generators lazy evaluation mapping
Python
def lazy_map(items, transform):
    for item in items:
        yield transform(item)

def double(x):
    return x * 2

def upper(s):
    return s.upper()

if __name__ == "__main__":
    numbers = [1, 2, 3, 4, 5]
    doubled = lazy_map(numbers, double)
    print("Doubled numbers:", end=" ")
    for value in doubled:
  …
14 0 Open
Comprehensions & generators easy

How to Use starmap() to Unpack Tuple Arguments in Python

Use itertools.starmap to apply a function to each tuple in an iterable, unpacking tuple elements as separate arguments and returning an iterator of results.

itertools starmap generators
Python
from itertools import starmap

def multiply(a, b):
    return a * b

if __name__ == "__main__":
    pairs = [(2, 3), (4, 5), (6, 7), (8, 9)]
    results = list(starmap(multiply, pairs))
    print(results)
14 0 Open
Comprehensions & generators easy

Memory efficient map over large file in Python

A generator-based streaming map that processes a large file line by line without loading the whole file into memory.

generator file-io streaming
Python
import sys

def process_lines(file_path):
    """Memory-efficient map over a large file: yields processed lines."""
    with open(file_path, 'r') as f:
        for line in f:
            # Example mapping: strip whitespace and uppercase
            yield line.strip().upper()

if __name__ == "__main__":
    # Use a sma…
12 0 Open
AI & LLM integration patterns medium

How to parallel map embeddings with a thread pool in Python

Run embedding computations in parallel using ThreadPoolExecutor, collect results into a dict keyed by the original item.

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


def compute_embedding(item: int) -> tuple[int, int]:
    time.sleep(0.05)  # Simulate embedding work
    return item, item * 10


def parallel_map_embed(items, max_workers=3):
    results = {}
    with ThreadPoolExecutor(max_workers=max_w…
15 0 Open
AI & LLM integration patterns easy

Route Tool Call Name to Python Handler Dict

Routes a tool call name to the correct Python handler function using a dictionary lookup, returning an error for unknown tools.

tool-calls llm-integration dictionary-mapping
Python
def get_name():
    return {"name": "Alice"}

def get_age():
    return {"age": 30}

def get_email():
    return {"email": "alice@example.com"}

handlers = {
    "get_name": get_name,
    "get_age": get_age,
    "get_email": get_email,
}

def route(tool_call):
    handler = handlers.get(tool_call["name"])
    if handl…
12 0 Open
Automation & scripting medium

Build a Complete Website Sitemap Generator Without External Services

Crawl a website recursively using only Python's standard library to generate a structured sitemap of internal links.

sitemap web-crawler html-parser
Python
import json
from urllib.parse import urlparse, urljoin
from collections import deque
import urllib.request
import urllib.error
import re
from html.parser import HTMLParser

class SitemapParser(HTMLParser):
    def __init__(self, base_url):
        super().__init__()
        self.base_url = base_url
        self.links …
44 0 Open
Automation & scripting easy

How to Map Network Drive Paths to Local Paths in Python

Convert mock SMB network drive paths (like 'S:\reports\q1.xlsx') to local placeholder paths and back using a simple mapping dictionary in Python.

network path-mapping smb
Python
"""Map mock SMB network drive paths to local placeholder paths."""
from dataclasses import dataclass

@dataclass(frozen=True)
class NetworkDrive:
    letter: str
    remote_path: str

DRIVES = {
    "S:": NetworkDrive("S", r"\\server01\shares\sales"),
    "M:": NetworkDrive("M", r"\\server02\media\movies"),
    "X:": …
15 0 Open
Data pipelines & processing easy

How to Group Rows by Key into Nested Arrays in Python

This code groups rows in a list of dictionaries by a specified key and returns a dictionary with each key mapped to a list of values from another key.

grouping defaultdict data-aggregation
Python
from collections import defaultdict


def implode_rows(rows, key, value_key):
    grouped = defaultdict(list)
    for row in rows:
        grouped[row[key]].append(row[value_key])
    return dict(grouped)


if __name__ == "__main__":
    data = [
        {"category": "fruit", "item": "apple"},
        {"category": "fr…
14 0 Open
Data pipelines & processing easy

How to Reduce Aggregate Counts from Mapped Chunks in Python

Combine a list of mapped chunk dictionaries into a single aggregated count dictionary using functools.reduce.

reduce aggregation dictionary
Python
from functools import reduce
from collections import defaultdict

def aggregate_chunks(mapped_chunks):
    """Combine mapped chunk counts into a single aggregate dict."""
    return reduce(
        lambda acc, chunk: {
            **acc,
            **{k: acc.get(k, 0) + v for k, v in chunk.items()}
        },
       …
14 0 Open
Data pipelines & processing medium

Map Partition Over Chunks in Python with Multiprocessing and Mock

Process data in chunks across multiple CPU cores using multiprocessing Pool.map, and mock the chunk function to test partitioning behavior without heavy computation.

multiprocessing chunking parallel
Python
from multiprocessing import Pool
from unittest.mock import patch, Mock

def process_chunk(chunk):
    return [x * x for x in chunk]

def map_partition_over_chunks(data, chunk_size, process_func=process_chunk):
    chunks = [data[i:i + chunk_size] for i in range(0, len(data), chunk_size)]
    with Pool() as pool:
     …
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
Modern tooling easy

Build a Recipe Runner Mock in Python

A Python script that mocks a command runner recipe system: maps recipe names to shell commands, executes them with subprocess, and prints the output and exit code.

subprocess command-runner recipes
Python
import subprocess
import sys


def run_recipe(recipe: str) -> None:
    """Simulate a command runner recipe by printing the command and exit code."""
    print(f"Running recipe: {recipe}")
    result = subprocess.run(recipe, shell=True, capture_output=True, text=True)
    print(f"Exit code: {result.returncode}")
    i…
14 0 Open
Concurrency & performance medium

How to Use ProcessPoolExecutor for CPU Parallel Map in Python

Run a function over a sequence of inputs in parallel across multiple CPU cores with ProcessPoolExecutor.map.

concurrency processpoolexecutor parallelism
Python
from concurrent.futures import ProcessPoolExecutor
import math

def compute_square(num):
    return num * num

def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(math.sqrt(n)) + 1):
        if n % i == 0:
            return False
    return True

if __name__ == "__main__":
    numbers = rang…
11 0 Open
Concurrency & performance medium

How to Use Thread Pool Executor map for IO-Bound Tasks in Python

Run multiple I/O-bound tasks concurrently with ThreadPoolExecutor map and collect their results in order.

threadpool concurrency io-bound
Python
import time
from concurrent.futures import ThreadPoolExecutor

def io_bound_task(task_id: int) -> str:
    time.sleep(0.2)  # mock I/O wait
    return f"Task {task_id} completed"

def main() -> None:
    task_ids = [1, 2, 3, 4, 5]
    with ThreadPoolExecutor(max_workers=3) as executor:
        results = list(executor.…
12 0 Open
Concurrency & performance easy

How to Use ThreadPoolExecutor in Python for Parallel Processing

Use ThreadPoolExecutor with executor.map to run a function over many inputs concurrently and collect ordered results.

concurrency threadpoolexecutor parallel
Python
def worker(item):
    return item * item

if __name__ == "__main__":
    from concurrent.futures import ThreadPoolExecutor
    numbers = list(range(1, 11))
    with ThreadPoolExecutor(max_workers=4) as executor:
        results = list(executor.map(worker, numbers))
    print("Input:  ", numbers)
    print("Results:", …
13 0 Open
Concurrency & performance medium

How to Use multiprocessing Pool map and starmap in Python

Parallelize functions over iterables with Pool.map, and unpack multiple arguments via Pool.starmap.

multiprocessing parallelism pool
Python
from multiprocessing import Pool


def square(x):
    return x * x


def add_and_multiply(a, b, c):
    return (a + b) * c


if __name__ == "__main__":
    numbers = [1, 2, 3, 4, 5]
    with Pool(processes=2) as pool:
        squares = pool.map(square, numbers)
        print(f"squares: {squares}")

        starmap_arg…
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 medium

Limit Concurrency with asyncio.Semaphore in Python

Use asyncio.Semaphore to cap how many async tasks run at once, throttling a batch of coroutines to a set concurrency limit.

asyncio concurrency semaphore
Python
import asyncio
import random


async def fetch_data(i: int, semaphore: asyncio.Semaphore) -> str:
    async with semaphore:
        print(f"Task {i} starts")
        await asyncio.sleep(random.uniform(0.1, 0.5))
        print(f"Task {i} finishes")
        return f"Result {i}"


async def main() -> None:
    semaphore …
13 0 Open
Concurrency & performance medium

Thread Pool Map for IO Bound Tasks in Python

Run IO-bound mock tasks concurrently with ThreadPoolExecutor.map and measure total elapsed time in Python.

threading concurrency threadpoolexecutor
Python
import concurrent.futures
import time
from pathlib import Path

def mock_io_task(filename):
    """Simulate an IO-bound task by creating a small file and measuring its latency."""
    path = Path(filename)
    path.write_text("data")
    time.sleep(0.1)  # Simulate slow disk/network
    return f"{filename} written in …
14 0 Open
System design patterns easy

How to Implement a Data Helper Class in Python

Build a beginner-friendly DataHelper class using dataclasses and key system design patterns like Command, Strategy, and Map.

dataclass data-helper design-patterns
Python
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional


@dataclass
class DataHelper:
    """A beginner-friendly data utility with common system design patterns."""
    data: List[Dict[str, Any]] = field(default_factory=list)

    def add_record(self, r…
13 0 Open
System design patterns easy

How to Implement a Factory Method by Type String in Python

A factory method maps a type string to a class, creating and returning the appropriate object instance while handling unknown types gracefully.

factory-pattern design-patterns oop
Python
class Animal:
    def speak(self):
        raise NotImplementedError


class Dog(Animal):
    def speak(self):
        return "Woof!"


class Cat(Animal):
    def speak(self):
        return "Meow!"


class AnimalFactory:
    @staticmethod
    def create(animal_type: str) -> Animal:
        animal_types = {
          …
14 0 Open
System design patterns medium

How to Limit Concurrent Requests with a Semaphore in Python

Use threading.Semaphore with a ThreadPoolExecutor to cap how many worker threads run simultaneously, preventing resource overload.

concurrency semaphore threading
Python
import threading
import time
from concurrent.futures import ThreadPoolExecutor

def worker(name, semaphore, results):
    with semaphore:
        results.append(f"start {name}")
        time.sleep(0.5)  # simulate async work
        results.append(f"done {name}")

def main():
    sem = threading.Semaphore(2)  # max 2 …
14 0 Open
System design patterns medium

Implement a Consistent Hash Ring in Python

Build a minimal consistent hash ring with virtual nodes to map keys to servers stably as nodes are added or removed.

consistent-hashing hashing distributed-systems
Python
import hashlib
import bisect


class ConsistentHashRing:
    def __init__(self, nodes=None, replicas=3):
        self.replicas = replicas
        self.ring = {}
        self.sorted_keys = []
        if nodes:
            for node in nodes:
                self.add_node(node)

    def _hash(self, key):
        return i…
15 0 Open
System design patterns easy

Route Messages to Handlers with a Python Dict

This code demonstrates a simple message routing pattern using a dictionary to map topic keys to handler functions, with a default handler for unmatched topics.

routing dictionary message-broker
Python
def route_message(message, routing_table):
    """Route a message to the correct handler based on the topic key."""
    topic = message.get("topic", "default")
    handler = routing_table.get(topic, routing_table.get("default"))
    return handler(message)


def handle_orders(message):
    return f"Orders handler proc…
12 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.