Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable 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 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…
Segregate Negative Numbers Before Positives in Python
Reorders a list so all negative numbers appear before non-negative numbers while preserving the original relative order of elements.
def segregate_negatives(numbers):
"""Segregate negatives before positives without altering relative order."""
negatives = [n for n in numbers if n < 0]
positives = [n for n in numbers if n >= 0]
return negatives + positives
if __name__ == "__main__":
sample = [3, -1, 4, -5, 2, -9, 0]
result =…
How to Delegate Iteration to a Subgenerator with yield from in Python
Use yield from to delegate iteration from one generator to a subgenerator, flattening nested generator output into a single sequence.
def subgenerator():
yield "first"
yield "second"
yield "third"
def delegate():
yield "before delegation"
yield from subgenerator()
yield "after delegation"
if __name__ == "__main__":
for item in delegate():
print(item)
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):
"…
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.
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)}")
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.
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…
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_…
Add a UUID Surrogate Key to Each Row in a CSV with Python
Generate a unique UUID string for every row in a CSV file using the standard-library uuid and csv modules.
import uuid
import csv
def add_surrogate_key(filename):
with open(filename, newline='') as f_in:
reader = csv.DictReader(f_in)
rows = list(reader)
for row in rows:
row['surrogate_key'] = str(uuid.uuid4())
with open(filename, 'w', newline='') as f_out:
writer = csv.DictWri…
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 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 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.
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…
How to Parse an AWS API Gateway Proxy Event in Python
Extract and parse common fields from a mock API Gateway proxy event, turning the JSON body into a native Python dict.
import json
from typing import Any, Dict, Optional
def parse_proxy_event(event: Dict[str, Any]) -> Dict[str, Any]:
"""Extract and parse common fields from an API Gateway proxy event."""
body = event.get("body", "")
if isinstance(body, str):
body = json.loads(body) if body else {}
elif body is…
How to Cancel an asyncio Task with Graceful Cleanup in Python
Cancel a running asyncio task, handle the cancellation signal inside a worker coroutine to perform cleanup, then re-raise so the cancellation propagates correctly.
import asyncio
async def worker(name: str, sleep: float) -> None:
try:
print(f"{name}: starting")
await asyncio.sleep(sleep)
print(f"{name}: completed")
except asyncio.CancelledError:
print(f"{name}: cancelled, cleaning up...")
await asyncio.sleep(0.2) # Simulate clea…
How to Use Stubs, Fakes, Spies, and Mocks in Python Testing
Implement four types of test doubles — stubs, fakes, spies, and mocks — as subclasses of a PaymentGateway interface to replace real dependencies during testing.
class PaymentGateway:
def charge(self, amount):
raise NotImplementedError
class StubPaymentGateway(PaymentGateway):
"""Returns a fixed response without any logic."""
def charge(self, amount):
return {"success": True, "transaction_id": "stub-12345"}
class FakePaymentGateway(PaymentGatewa…
Interface Segregation with Fake Test Implementations in Python
Defines segregated abstract interfaces (Printer, Scanner) and uses a FakePrinter to record calls for unit testing without real resources.
from abc import ABC, abstractmethod
class Printer(ABC):
@abstractmethod
def print_document(self, doc: str) -> str:
pass
class Scanner(ABC):
@abstractmethod
def scan_document(self) -> str:
pass
class MultiFunctionPrinter(Printer, Scanner):
def print_document(self, doc: str) -> …
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.
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 [
{…
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.
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:
…
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 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.
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…
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 Propagate X-Request-ID in Python
Generate a unique request ID when one is missing and pass it through API calls for distributed tracing.
import uuid
def generate_request_id() -> str:
"""Generate a unique request ID similar to X-Request-ID header."""
return str(uuid.uuid4())
def propagate_request_id(request_id: str | None) -> str:
"""Return the request ID for propagation, generating one if missing."""
if request_id:
return re…
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.