Reference library

Python Code Samples

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

25 matches
Functions & basics easy

How to Use functools.reduce in Python

Apply functools.reduce with operator functions and lambda expressions to aggregate lists into sums, products, maximums, and concatenated strings.

reduce functools lambda
Python
from functools import reduce
import operator

# Sum all numbers in a list using reduce
numbers = [1, 2, 3, 4, 5]
sum_result = reduce(operator.add, numbers)

# Find the maximum value using reduce
max_result = reduce(lambda a, b: a if a > b else b, numbers)

# Multiply all numbers using reduce
product_result = reduce(la…
12 0 Open
Files & data easy

Generate Timesheet Reports from Daily Logs in Python

Aggregate daily log entries by project and produce a formatted timesheet report using Python's standard library.

timesheet reporting aggregation
Python
import json
from pathlib import Path
from collections import defaultdict

def generate_timesheet_report(daily_logs: list[dict]) -> str:
    """
    Generate a timesheet report from daily log entries.
    
    Args:
        daily_logs: List of dicts with 'date', 'project', 'hours', 'task' keys
    
    Returns:
       …
45 0 Open
Dictionaries & sets easy

How to Aggregate Order Data with Sets and Dictionaries in Python

Combine sets and dictionaries to find unique products and total quantities from a list of orders in Python.

sets dictionaries data aggregation
Python
def find_unique_products(orders):
    """Return set of all products ordered across multiple orders."""
    all_products = set()
    for order in orders:
        all_products.update(order.get("items", []))
    return all_products


def product_summary(orders):
    """Build a dictionary mapping each product to its total…
13 0 Open
Comprehensions & generators easy

How to Parse Data with Generators and Comprehensions in Python

This code demonstrates using a generator expression to filter active users and a dictionary comprehension to aggregate scores by name.

generator expressions dictionary comprehensions filtering
Python
def parse_data_helper(raw_records):
    """Extract active users' names and scores from raw records."""
    parsed = (
        (record["name"], record["score"])
        for record in raw_records
        if record["active"] and record["score"] >= 0
    )
    return list(parsed)


def aggregate_scores(parsed_data):
    "…
15 0 Open
Comprehensions & generators easy

Sum of Squares with a Generator Expression in Python

This code computes the sum of squares of integers from 1 to n using a generator expression, demonstrating a memory-efficient and concise way to aggregate a sequence.

generator sum squares
Python
def sum_of_squares(n):
    return sum(x * x for x in range(1, n + 1))

if __name__ == "__main__":
    print(f"Sum of squares from 1 to 5: {sum_of_squares(5)}")
    print(f"Sum of squares from 1 to 10: {sum_of_squares(10)}")
14 0 Open
Automation & scripting easy

Aggregate Log Errors Count by Hour in Python

Counts ERROR log lines per hour using regex and Counter, returning a sorted dictionary of hourly totals.

logs regex counter
Python
import re
from collections import Counter
from datetime import datetime

def aggregate_errors_by_hour(log_lines):
    pattern = re.compile(r'^(\d{4}-\d{2}-\d{2} \d{2}):\d{2}:\d{2}.*ERROR')
    hourly_counts = Counter()
    
    for line in log_lines:
        match = pattern.match(line)
        if match:
            ho…
20 0 Open
Automation & scripting easy

Generate a Monthly Report CSV from Log Files in Python

Reads a CSV log file, filters events by a given month, aggregates daily event counts and revenue, and writes a summarized monthly report to a new CSV.

csv logs report
Python
import csv
from collections import defaultdict
from datetime import datetime

def generate_monthly_report(log_file: str, month: str, output_file: str) -> None:
    events_by_date = defaultdict(int)
    revenue_by_date = defaultdict(float)
    
    with open(log_file, 'r') as f:
        for line in f:
            date_…
14 0 Open
Data pipelines & processing easy

How to Build Data Processing Functions in Python

Create reusable helper functions to load, filter, transform, and aggregate CSV data in Python.

csv pipeline etl
Python
import csv
from pathlib import Path


def load_data(filepath):
    """Load CSV data into a list of dicts."""
    with open(filepath, "r", newline="", encoding="utf-8") as f:
        return list(csv.DictReader(f))


def filter_rows(rows, column, value):
    """Keep rows where column equals value."""
    return [row for…
11 0 Open
Data pipelines & processing easy

How to Build a Simple Data Pipeline in Python

A beginner-friendly data pipeline that loads JSON, filters records by a field value, and aggregates counts per category.

pipeline json aggregation
Python
import json
from pathlib import Path


def load_json(filepath: str | Path) -> list[dict]:
    """Load a JSON file containing a list of records."""
    with Path(filepath).open("r", encoding="utf-8") as f:
        return json.load(f)


def filter_records(records: list[dict], field: str, value) -> list[dict]:
    """Kee…
10 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
Cloud + Python easy

How to Design a Cloud Data Helper Class in Python

A beginner-friendly Python helper class that saves, loads, and aggregates JSON records locally, simulating cloud-style data handling.

cloud json helper
Python
import json
from pathlib import Path
from datetime import datetime


class CloudDataHelper:
    """Beginner-friendly helper for working with cloud-based JSON data."""

    def __init__(self, base_dir="cloud_data"):
        self.base_dir = Path(base_dir)
        self.base_dir.mkdir(exist_ok=True)

    def save_record(s…
11 0 Open
System design patterns medium

Build a BFF (Backend for Frontend) Mock Aggregator in Python

A minimal HTTP server implementing the BFF pattern that aggregates user data and orders from two mock backends into a single JSON response.

bff http-server aggregation
Python
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse


class MockBackendA:
    def get_user(self, user_id):
        return {"id": user_id, "name": "Alice", "service": "backend-a"}


class MockBackendB:
    def get_orders(self, user_id):
        return [
            {…
17 0 Open
System design patterns medium

Domain Driven Design Aggregate Root Example in Python

Model an Order as an aggregate root with invariants enforced through methods, demonstrating DDD principles in Python.

ddd aggregate-root object-oriented
Python
from __future__ import annotations
from dataclasses import dataclass
from typing import List, Optional
from uuid import uuid4


class Money:
    def __init__(self, amount: float, currency: str = "USD"):
        self.amount = amount
        self.currency = currency

    def __add__(self, other: Money) -> Money:
       …
12 0 Open
System design patterns easy

How to Aggregate Mock API Routes by Method in Python

Groups mock API routes by path and method, collecting response bodies and counts into a nested dictionary structure.

defaultdict api-gateway aggregation
Python
from collections import defaultdict


def aggregate_mock_routes(routes):
    """Aggregate mock API routes by method and aggregate their response bodies."""
    aggregated = defaultdict(lambda: defaultdict(list))

    for route in routes:
        method = route["method"]
        path = route["path"]
        response = …
13 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 Take Periodic Snapshots of Aggregate State in Python

Build a Python class that accumulates values and periodically captures immutable snapshots of total, count, and average for later analysis.

aggregation snapshots state-management
Python
import time
import random
from collections import defaultdict


class SnapshotAggregator:
    def __init__(self):
        self.total = 0
        self.count = 0
        self.history = []

    def add(self, value):
        self.total += value
        self.count += 1

    def snapshot(self):
        avg = self.total / se…
13 0 Open
Streaming & messaging easy

Event sourcing append store replay in Python

A simple in-memory event store that appends events per aggregate and replays them on demand.

event-sourcing append-only replay
Python
import json
from collections import defaultdict


class EventStore:
    def __init__(self):
        self._events = defaultdict(list)

    def append(self, aggregate_id, event_type, data):
        event = {"type": event_type, "data": data}
        self._events[aggregate_id].append(event)

    def replay(self, aggregate…
14 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
Observability & SRE easy

How to Process System Metrics (RSS, CPU) in Python

Simulate and aggregate RSS and CPU system metrics to compute averages and maximums for monitoring dashboards.

metrics rss cpu
Python
import random
import time
from collections import namedtuple

Metric = namedtuple("Metric", ["name", "value", "unit"])


def generate_metrics(num_metrics: int = 5) -> list:
    """Simulate a batch of system metrics."""
    metrics = []
    for i in range(num_metrics):
        rss = random.randint(50, 500)  # MB
      …
12 0 Open
Microservices patterns easy

BFF aggregation pattern: combine multiple service responses in Python

Mock three backend services and aggregate their responses into one unified payload — the BFF pattern every Python microservice gateway relies on.

bff aggregation microservices
Python
from dataclasses import dataclass
from typing import Any


@dataclass
class Service:
    name: str
    data: dict[str, Any]


def get_user_service() -> Service:
    return Service("user", {"id": 1, "name": "Alice"})


def get_orders_service() -> Service:
    return Service("orders", {"total": 299.99, "count": 2})


de…
12 0 Open
Microservices patterns easy

Scatter Gather Aggregate Pattern in Python

Simulates a scatter/gather/aggregate pattern by distributing work across items, gathering results, and aggregating them.

scatter-gather aggregation pattern
Python
import random

def process_items(items, scatter_fn, gather_fn, aggregate_fn):
    """Simple scatter/gather/aggregate pattern simulation."""
    scattered = [scatter_fn(item) for item in items]
    gathered = [gather_fn(item) for item in scattered]
    return aggregate_fn(gathered)

if __name__ == "__main__":
    data …
13 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
Big data & Spark easy

How to Pivot and Group Aggregate in Python

Group records by a key, collect values, and apply an aggregate function (like sum) to build a pivot-style summary dictionary.

pivot group-by aggregation
Python
from collections import defaultdict

def pivot_group_aggregate(records, group_key, value_key, agg_func):
    groups = defaultdict(list)
    for record in records:
        groups[record[group_key]].append(record[value_key])
    return {key: agg_func(values) for key, values in groups.items()}

if __name__ == "__main__":…
13 0 Open
Big data & Spark medium

How to Simulate a MapReduce Mock with Combine Phase in Python

Simulates a MapReduce pipeline with a combiner that aggregates local counts per reducer to reduce network and compute overhead.

mapreduce combiner hadoop
Python
from collections import defaultdict

def map_phase(lines):
    intermediate = defaultdict(list)
    for line in lines:
        for word in line.strip().lower().split():
            intermediate[word].append(1)
    return dict(intermediate)

def combine_phase(intermediate, num_reducers=3):
    combined = defaultdict(li…
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.