Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
Generate Data Helper for Beginners in Python
Define two functions that create a random list of integers and then compute basic summary statistics like count, total, average, maximum, and minimum using simple loops.
from random import randint
def build_dataset(size: int, max_val: int) -> list[int]:
data = []
for _ in range(size):
data.append(randint(1, max_val))
return data
def summarize(data: list[int]) -> dict[str, float]:
total = 0
maximum = data[0]
minimum = data[0]
for value in data:
…
Build a Personal Work Hours Tracker in Python
A Python class that logs daily work hours to a CSV file and produces a weekly summary of total hours worked.
import csv
from pathlib import Path
from datetime import datetime, date
class WorkHoursTracker:
def __init__(self, file_path="work_hours.csv"):
self.file_path = Path(file_path)
if not self.file_path.exists():
with open(self.file_path, "w", newline="") as f:
writer = csv…
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…
Group Data Helper Class in Python
A simple Python class that stores items under named groups, retrieves groups, items, and counts, and formats them as a readable summary.
class GroupData:
"""A simple helper class to store and group data for beginners."""
def __init__(self):
self.items = []
def add(self, item, group):
"""Add an item under a given group name."""
self.items.append({"item": item, "group": group})
def get_groups(self):
"""R…
How to Count Items in a Python Class
A beginner-friendly Inventory class that stores item quantities in a dictionary and provides add, remove, count, and summary methods.
class Inventory:
def __init__(self):
self.items = {}
def add(self, item, quantity=1):
self.items[item] = self.items.get(item, 0) + quantity
def remove(self, item, quantity=1):
if item not in self.items:
raise ValueError(f"{item} not in inventory")
self.items[it…
How to Use Comprehensions and Generators to Check Data in Python
A beginner-friendly helper that filters numeric values, computes squares and cubes with comprehensions and a generator, and returns a summary dictionary.
def check_data(iterable):
"""Return a summary of numeric data using comprehensions and a generator."""
values = [item for item in iterable if isinstance(item, (int, float))]
squares = [x ** 2 for x in values if x > 0]
cubes = (x ** 3 for x in values if x > 0)
cube_list = list(cubes)
return {
…
How to Log Prompts and Completions as JSONL Audit Files in Python
Read a JSONL file of LLM prompt–completion pairs, compute totals and averages, then write an audit summary with timestamps.
import json
from pathlib import Path
from datetime import datetime
def audit_jsonl(filepath):
logs = []
with open(filepath, encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
entry = json.loads(line)
logs.ap…
How to Summarize Old Conversation Turns in Python
Compress old conversation turns into a brief summary while keeping recent turns intact for LLM context management.
from datetime import datetime, timedelta
def summarize_old_turns(conversation, max_turns=5):
"""Compress turns older than max_turns into a brief summary."""
if len(conversation) <= max_turns:
return conversation, ""
old_turns = conversation[:-max_turns]
recent_turns = conversation[-max_turns…
How to compute ROUGE recall in Python
Compute ROUGE recall by counting token overlap between a reference and candidate summary with pure Python.
def rouge_recall(reference, candidate):
ref_tokens = reference.lower().split()
cand_tokens = candidate.lower().split()
ref_counts = {}
for token in ref_tokens:
ref_counts[token] = ref_counts.get(token, 0) + 1
cand_counts = {}
for token in cand_tokens:
cand_counts[token] = cand…
Prepare LLM prompt data with a Python helper class
A beginner-friendly Python class that collects records, converts them to JSON, and produces a quick summary for building LLM prompt context.
import json
from typing import Any, Dict, List
class DataHelper:
"""Simple helper to prepare data for LLM prompts."""
def __init__(self):
self.data = []
def add(self, item: Dict[str, Any]) -> "DataHelper":
self.data.append(item)
return self
def to_json(self) -> s…
Generate Beautiful Project Documentation from Python Source Code Automatically
Automatically generate a markdown summary of function docstrings from any Python source file using the AST module.
import ast
import inspect
from pathlib import Path
def extract_docstrings_from_file(filepath):
"""Parse a Python file and collect function docstrings."""
source = Path(filepath).read_text()
tree = ast.parse(source)
docs = []
for node in ast.walk(tree):
if isinstance(node, (ast.FunctionDef…
Run pytest and email summary in Python
Runs pytest via subprocess, extracts the test summary line, and sends it in an email (mocked for demonstration).
import smtplib
import subprocess
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def run_tests():
"""Run pytest and capture the summary output."""
result = subprocess.run(
["pytest", "-q"],
capture_output=True,
text=True
)
return result.stdo…
How to Group Data by Key in Python with Type Hints
Group a list of dictionaries by a specified key using a typed helper function and print a summary of each group.
from typing import Any, Dict, List, TypeVar, Union
T = TypeVar("T")
def group_by(data: List[Dict[str, Any]], key: str) -> Dict[Any, List[Dict[str, Any]]]:
"""Group a list of dictionaries by a given key."""
grouped: Dict[Any, List[Dict[str, Any]]] = {}
for item in data:
value = item.get(key)
…
Summary Quantile Mock Sketch in Python
Build a memory-efficient sketch that stores sorted bins of data points to answer approximate quantile queries like median without keeping all values in memory.
import random
import statistics
from collections import Counter
class SummaryQuantileSketch:
"""
A simple sketch that stores a fixed-size summary of data (min, max, deciles)
using sorted bins, then answers approximate quantile queries.
"""
def __init__(self, bins=10):
self.bins = bins
…
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__":…
How to Simulate an Airflow ML Pipeline in Python
Mock an Airflow ML pipeline in plain Python by defining steps, simulating their execution with delays, and returning a success summary.
from datetime import datetime, timedelta
import time
class MLPipeline:
def __init__(self, pipeline_name):
self.pipeline_name = pipeline_name
self.steps = []
def add_step(self, step_name, duration_seconds):
self.steps.append({"name": step_name, "duration": duration_seconds})
def …
How to mock batch commit of transactions in Python
Simulate a transaction batch writer with commit, rollback, and summary logic to test database write patterns without a real database.
import json
from datetime import datetime, timezone
class TransactionBatch:
def __init__(self):
self.pending = []
self.committed = []
self._log = []
def add(self, operation):
self.pending.append(operation)
def commit(self):
if not self.pending:
return …
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.