Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
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.
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…
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.
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:
…
How to Sum a CSV Column by Group in Python
This code reads a CSV string and sums a specified column for each unique value of a group key using the csv module and defaultdict.
import csv
from collections import defaultdict
from io import StringIO
def aggregate_csv(csv_data, group_key, sum_column):
totals = defaultdict(float)
reader = csv.DictReader(StringIO(csv_data))
for row in reader:
key = row[group_key]
totals[key] += float(row[sum_column])
return dict(t…
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.
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…
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.
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):
"…
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.
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_…
How to Build Data Processing Functions in Python
Create reusable helper functions to load, filter, transform, and aggregate CSV data in 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…
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.
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…
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.
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…
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.
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()}
},
…
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.
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 = …
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.
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…
How to Implement a Tumbling Window Counter in Python
Count events that fall within a fixed-size sliding time window using a deque and pruning logic.
from collections import deque
import time
class TumblingWindowCounter:
def __init__(self, window_size_seconds):
self.window_size = window_size_seconds
self.window = deque()
def add_event(self, timestamp):
self.window.append(timestamp)
def count(self, current_time):
while…
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.
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…
Scatter Gather Aggregate Pattern in Python
Simulates a scatter/gather/aggregate pattern by distributing work across items, gathering results, and aggregating them.
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 …
How to Implement collect_list in Python
Group rows by a key and collect all corresponding values into a list — a pure-Python mock of Spark's collect_list aggregation.
from collections import defaultdict
def collect_list(rows, key_field, value_field):
grouped = defaultdict(list)
for row in rows:
grouped[row[key_field]].append(row[value_field])
return dict(grouped)
if __name__ == "__main__":
data = [
{"dept": "sales", "emp": "alice"},
{"dept"…
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.
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__":…
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
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- 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.