Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Round Numbers with f-strings in Python
Round numbers directly inside f-string expressions using the built-in round() function for clean, readable output formatting.
def main():
# Values to format with expression-based rounding
price = 19.995
tax_rate = 0.0825
distance = 1234.56789
# Round inside the f-string expression using round()
print(f"Price rounded to cents: ${round(price, 2)}")
# Combine rounding with arithmetic inside the expression
total…
How to wrap long text to a specified width in Python
Uses Python's textwrap.fill to wrap a long string to a specified width at word boundaries, preserving readability in console output or logs.
import textwrap
text = """This is a long piece of text that definitely exceeds the width limit
if we try to print it on a single line without any wrapping applied."""
wrapped = textwrap.fill(text, width=40)
print(wrapped)
How to Flatten One Level of a Nested List in Python
Flattens exactly one level of a nested list by extending the output with each inner list and appending non-list items.
def flatten_one_level(nested_list):
"""Flatten one level of a nested list."""
flattened = []
for item in nested_list:
if isinstance(item, list):
flattened.extend(item)
else:
flattened.append(item)
return flattened
if __name__ == "__main__":
# Example with mi…
How to unzip a list of pairs into two lists in Python
Split a list of (a, b) tuples into two separate lists by iterating with a for loop and appending each element to its own output list.
def unzip(pairs):
"""Split a list of (a, b) pairs into two separate lists."""
if not pairs:
return [], []
firsts = []
seconds = []
for a, b in pairs:
firsts.append(a)
seconds.append(b)
return firsts, seconds
if __name__ == "__main__":
pairs = [(1, 'a'), (…
How to Debug Print Behind a DEBUG Environment Flag in Python
Create a debug_print function that only outputs when the DEBUG environment variable is set to a truthy value like 1, true, yes, or on.
import os
def debug_print(*args, **kwargs):
"""Print only when DEBUG environment variable is set to a truthy value."""
if os.environ.get("DEBUG", "").lower() in ("1", "true", "yes", "on"):
print(*args, **kwargs)
if __name__ == "__main__":
# Example usage: run as `DEBUG=1 python script.py` to se…
Redact secrets from log message formatter in Python
Build a custom logging.Formatter that masks passwords, API keys, and credit card numbers in log output.
import re
import logging
class RedactingFormatter(logging.Formatter):
"""Formatter that masks sensitive data in log messages."""
SENSITIVE_PATTERNS = [
(re.compile(r'password[=:]\s*\S+', re.IGNORECASE), 'password=[REDACTED]'),
(re.compile(r'api[_-]?key[=:]\s*\S+', re.IGNORECASE), 'api_key…
Use pprint for Nested Structure Debug Output in Python
Pretty-print nested dictionaries and lists with pprint for readable, organized debug output.
from pprint import pprint
def build_nested_structure():
"""Create a sample nested data structure for demonstration."""
return {
"project": "DataPipeline",
"config": {
"inputs": ["raw_1.json", "raw_2.json"],
"processing": {
"steps": ["clean", "transform",…
Extract a Single Member from a ZIP Archive in Python
Extract one specific file from a ZIP archive to an output directory using the standard zipfile and pathlib modules.
import zipfile
from pathlib import Path
def extract_single_member(zip_path: str, member_name: str, output_dir: str = ".") -> Path:
"""Extract a single member from a zip archive to the output directory."""
with zipfile.ZipFile(zip_path, "r") as archive:
archive.extract(member_name, output_dir)
retu…
How to Merge Sorted Chunk Files in Python
Merge multiple sorted text files into one sorted output file using a heap for efficient k-way merging.
import heapq
def merge_sorted_chunks(chunks, output_path):
"""Merge multiple sorted iterables into single sorted output file."""
with open(output_path, "w") as out_f:
# Open all chunk files
handles = [open(chunk, "r") for chunk in chunks]
try:
# Heap of (value, index) tupl…
Join two CSV files on shared key column in Python
Merge rows from two CSV files by a common key column, outputting combined records to a new file.
import csv
def join_csv(file1, file2, key, output="joined.csv"):
# Read first CSV into dict keyed by the join column
with open(file1, newline="") as f1:
reader1 = csv.DictReader(f1)
data1 = {row[key]: row for row in reader1}
# Read second CSV and merge matching rows
with open(file2, n…
Build adjacency dict graph from edges in Python
Convert a list of edges into an undirected adjacency dictionary, mapping each node to its neighbors, with sorted output.
def build_adjacency_dict(edges):
graph = {}
for u, v in edges:
if u not in graph:
graph[u] = []
if v not in graph:
graph[v] = []
graph[u].append(v)
graph[v].append(u)
return graph
if __name__ == "__main__":
edges = [(1, 2), (2, 3), (3, 4), (4, 1)…
How to Convert a Counter to a Plain Dict with Sorted Items in Python
This code converts a collections.Counter into a regular dictionary with items sorted by key, useful for stable, readable output.
from collections import Counter
def counter_to_sorted_dict(counter):
"""Convert a Counter to a plain dict with sorted items."""
return dict(sorted(counter.items()))
if __name__ == "__main__":
# Example usage
data = Counter(['apple', 'banana', 'apple', 'cherry', 'banana', 'date', 'apple'])
print("…
Stable merge two lists by custom comparator in Python
Merge two lists into one sorted output using a custom comparator while maintaining the original order of equal elements.
from functools import cmp_to_key
def compare(x, y):
# Custom comparator: sorts by length first, then by original index for stability
if len(x) != len(y):
return len(x) - len(y)
return 0 # Equal keys preserve original order (stable)
def merge_stable(left, right, cmp_func):
result = []
i =…
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 Reset Python's Random Seed for Deterministic Output
This code shows how to seed Python's random module to generate identical random sequences across runs, ensuring reproducibility.
import random
def seeded_random_sequence(seed, count=5, low=1, high=100):
random.seed(seed)
return [random.randint(low, high) for _ in range(count)]
if __name__ == "__main__":
seed_value = 42
first_run = seeded_random_sequence(seed_value)
print("First run:", first_run)
# Reset seed and gener…
How to Parse JSON from LLM Model Output Fence in Python
Extract and parse a JSON object from a language model's output that may be wrapped in triple-backtick fences with an optional language tag.
import json
import re
def parse_json_from_fence(text):
"""
Extract JSON object from a model output that may be wrapped in
triple-backtick fences with optional language tag.
"""
# Match content inside
How to Validate JSON Output Against a Dict Schema in Python
Validate JSON-like data against a simple dict schema with type checking and descriptive error messages using only the Python standard library.
from typing import Dict, Any, List, Union
def validate_json(data: Any, schema: Dict[str, str]) -> List[str]:
"""
Validate JSON-like data against a simple dict schema.
Schema format: {field_name: expected_type} where type is one of:
'str', 'int', 'float', 'bool', 'list', 'dict', 'any'
Returns list …
How to Validate LLM Output in Python
A beginner-friendly DataValidator class that checks required fields and type constraints on LLM-generated or user JSON data.
import json
from typing import Any, Dict, List, Optional
class DataValidator:
"""Simple helper for validating LLM-generated or user data."""
def __init__(self, required_fields: List[str], schema: Optional[Dict[str, str]] = None):
self.required_fields = required_fields
self.schema = schema or…
How to compute exact match metric in Python
Computes the exact match (EM) metric for LLM outputs by normalizing text and comparing predictions against references.
def compute_exact_match(predictions, references):
def normalize(text):
import re
text = text.lower().strip()
text = re.sub(r'\b(a|an|the)\b', ' ', text)
text = re.sub(r'[^a-z0-9\s]', '', text)
text = ' '.join(text.split())
return text
matches = sum(1 for pred, r…
How to parse JSON in Python: A Beginner's Guide with Code Examples
This guide shows you how to parse JSON data in Python step by step, with practical code examples and expected outputs.
import json
from typing import Any, Dict, List, Optional
class DataHelper:
"""Beginner-friendly helper for common AI/LLM data tasks."""
def __init__(self, data: Optional[Dict[str, Any]] = None):
self.data = data or {}
def to_prompt(self, template: str) -> str:
"""Format a prompt…
JSON Mode Prompt Schema Output in Python
Extract a user object to JSON with explicit schema keys, ready for LLM JSON-mode prompts.
import json
from typing import Any, Dict
def extract_user_as_json(user: Dict[str, Any]) -> str:
"""Extract a user object and return it as JSON using explicit schema keys."""
schema_fields = ("id", "name", "email", "is_active")
user_subset = {key: user[key] for key in schema_fields if key in user}
ret…
Automate Tweeting New Blog Posts in Python
A mock script that fetches new blog posts from a CMS and tweets them via a simulated Twitter API, outputting JSON results.
import json
import time
from datetime import datetime
def fetch_new_blog_posts():
"""Mock function to simulate fetching latest blog posts from a CMS."""
return [
{
"id": 1,
"title": "Getting Started with Python",
"url": "https://blog.example.com/python-start",
…
Fill PDF Form Fields from a Mock Template in Python
Fills a PDF-style form template dictionary with user data, preserving template fields and formatting output as JSON.
import json
template = {
"first_name": "",
"last_name": "",
"email": "",
"phone": "",
"date_of_birth": "",
"address": "",
"city": "",
"state": "",
"zip_code": "",
"agree_to_terms": False
}
def fill_pdf_form(template: dict, data: dict) -> dict:
for key, value in data.items…
Find Zombie Processes on Linux with Python
Parse the output of `ps -eo pid,stat,comm` to detect processes in zombie state (Z) on a Linux system and report their PIDs and commands.
#!/usr/bin/env python3
import os
import subprocess
def find_zombie_processes():
"""Find zombie processes (state 'Z') running on Linux."""
try:
result = subprocess.run(['ps', '-eo', 'pid,stat,comm'], capture_output=True, text=True, check=True)
zombies = []
for line in result.stdout.stri…
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.