Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Prune Empty Directories in Python with os.walk
Remove all empty subdirectories bottom-up using os.walk with topdown=False and os.rmdir, safely ignoring non-empty folders.
import os
def prune_empty_dirs(root):
"""Remove all empty subdirectories under root, bottom-up."""
for dirpath, dirnames, filenames in os.walk(root, topdown=False):
if dirpath == root:
continue
try:
os.rmdir(dirpath)
print(f"Removed: {dirpath}")
exce…
How to Sanitize Filenames in Python
Strip illegal filename characters and clean up names for safe filesystem use.
import re
from pathlib import Path
def sanitize_filename(filename: str, replacement: str = "_") -> str:
"""
Remove illegal characters from a filename.
Illegal characters: / \\ : * ? " < > |
Also strips leading/trailing spaces and dots.
"""
# Remove illegal characters
sanitized = re.su…
Read Entire File into String with read Method in Python
Open a file, read its entire content into a string using the .read() method, and clean up with a context manager.
from pathlib import Path
def read_file_to_string(file_path: str) -> str:
"""Read the entire file content into a string using the read method."""
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
return content
if __name__ == "__main__":
# Create a temporary file for d…
How to Normalize Data in Python with Dictionaries and Sets
Normalize a list of dicts by keeping selected keys, stripping/lowercasing strings, and extracting unique sorted values using set comprehension.
def normalize_data(data, keys):
"""
Normalize a list of dictionaries by keeping only specified keys
and converting values to proper types.
"""
normalized = []
for item in data:
clean_item = {}
for key in keys:
value = item.get(key)
if isinstance(value, st…
How to Normalize Data with Dictionaries and Sets in Python
Normalize dictionary entries to a fixed set of keys and extract unique values using sets in Python.
def normalize_entry(entry: dict, valid_keys: set) -> dict:
result = {}
for key in valid_keys:
result[key] = entry.get(key, "")
return result
def unique_values(entries: list[dict], key: str) -> set:
return {entry.get(key) for entry in entries if entry.get(key) is not None}
if __name__ == "__…
How to Recursively Remove None Values from Nested Dictionaries in Python
Recursively removes all None values from nested dictionaries and lists while preserving non-None data.
def prune_none(obj):
if isinstance(obj, dict):
return {
k: prune_none(v)
for k, v in obj.items()
if v is not None and prune_none(v) is not None
}
elif isinstance(obj, list):
pruned = [prune_none(item) for item in obj]
pruned = [item for item i…
How to Transform a List of Dictionaries with Sets in Python
Normalize a list of dict records — cleaning names, extracting unique tags with sets, and building a standardized result.
def transform_data(raw_records):
"""Transform a list of dict records into normalized data with sets for unique values."""
normalized = []
unique_names = set()
all_tags = set()
for record in raw_records:
# Normalize name to lowercase and strip whitespace
name = record.get("name"…
How to implement a Facade class to simplify subsystem calls in Python
Use a Facade class to wrap complex subsystem interactions behind a simple start() method, hiding the details and providing a clean interface.
class CPU:
def freeze(self):
print("CPU: freezing")
def jump(self, position):
print(f"CPU: jumping to {position}")
def execute(self):
print("CPU: executing")
class Memory:
def load(self, position, data):
print(f"Memory: loading '{data}' at {position}")
class HardDr…
Count Smaller Elements to the Right in Python
Return a list where each index counts how many elements to its right are smaller than that element using a clean O(n²) nested-loop approach.
def count_smaller_elements(arr):
"""
Return a list where result[i] is the number of elements
to the right of arr[i] that are smaller than arr[i].
"""
result = []
for i in range(len(arr)):
count = 0
for j in range(i + 1, len(arr)):
if arr[j] < arr[i]:
…
How to Replace Outliers Beyond Threshold with Cap in Python
Replace values that fall below a lower threshold or above an upper threshold by capping them to the threshold values using a simple Python function.
def replace_outliers_with_cap(data, lower_threshold=None, upper_threshold=None):
"""Replace values beyond given thresholds with the threshold values (capping)."""
if lower_threshold is None and upper_threshold is None:
raise ValueError("At least one threshold must be provided.")
capped_data = …
How to Close a Generator and Handle GeneratorExit in Python
This Python code demonstrates how to explicitly close a generator using the close() method and handle the GeneratorExit exception through a finally block to run cleanup logic.
def countdown(n):
try:
while n > 0:
yield n
n -= 1
finally:
print(f"Generator closed after countdown completed")
if __name__ == "__main__":
gen = countdown(5)
print(next(gen))
print(next(gen))
gen.close()
print("Generator closed explicitly")
Normalize Data in Python with Comprehensions and Generators
Clean a list by dropping None values with a comprehension, then min-max normalize it using a lazy generator expression — a beginner-friendly data preparation pattern.
import statistics
# Sample raw data including missing and outlier-ish values
raw = [22, 18, None, 25, 30, 19, 22, 17, None, 28, 24]
# Clean the data: drop None values using a list comprehension
clean = [x for x in raw if x is not None]
# Normalize using min-max scaling with a generator expression
min_val = min(clea…
How to Parse Chat Completion JSON in Python
Parse a mock OpenAI chat completion JSON response into a clean dictionary with content, finish reason, and model.
import json
def parse_chat_response(raw: str) -> dict:
data = json.loads(raw)
choice = data["choices"][0]
return {
"content": choice["message"]["content"],
"finish_reason": choice["finish_reason"],
"model": data["model"],
}
if __name__ == "__main__":
mock_response = '''
…
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…
Automatically Clean Temporary Files from Applications Using Python
A Python script that safely deletes temporary files from common application temp directories across Windows, Linux, and macOS, tracking cleaned count and disk space.
import os
import shutil
import tempfile
import platform
def clean_application_temp_files():
"""Delete common temporary file locations safely."""
system = platform.system()
temp_dirs = []
if system == "Windows":
temp_dirs.extend([
os.path.join(os.getenv("LOCALAPPDATA"), "Temp"),
…
Detect Memory Leaks in Python with Weak References
A custom LeakDetector uses weak references and garbage collection to find class instances that survive past expected cleanup in long-running Python applications.
import gc
import sys
import weakref
import time
from collections import defaultdict
class LeakDetector:
def __init__(self):
self._tracked = defaultdict(list)
def track_class(self, cls):
"""Track all instances of a class for leak detection."""
old_init = cls.__init__
def new_in…
Find Orphan Files Not Referenced Anywhere in Python
Scan a project directory for files whose names never appear in the content of other files, identifying potentially unused resources.
import os
from pathlib import Path
import re
def find_orphan_files(root_dir: str, extensions: set = None, ignore_patterns: list = None):
"""Find files not referenced by any other file in the project."""
if extensions is None:
extensions = {'.txt', '.md', '.py', '.html', '.css', '.js', '.json', '.yaml'…
How to Clean Old Temp Files in Python
A Python script that scans a directory and deletes files older than a configurable age (default: one week), with safe error handling.
import os
import time
from pathlib import Path
def clean_old_temp_files(directory=".", max_age_seconds=7 * 24 * 60 * 60):
"""
Remove files in directory older than the specified age.
Args:
directory: Path to directory to clean
max_age_seconds: Maximum age in seconds (default: 1 week)
…
How to Detect Unused Images in a Project with Python
A Python script that scans a website project folder, identifies all image files, and checks HTML/CSS/JS files to find which images are never referenced.
import os
import re
from pathlib import Path
def find_unused_images(project_path):
image_exts = {'.png', '.jpg', '.jpeg', '.gif', '.svg', '.webp'}
used_images = set()
all_images = set()
# Find all image files
for root, _, files in os.walk(project_path):
for file in files:
…
How to Filter Docker Containers for Pruning in Python
Simulate Docker's container prune by filtering a JSON list for exited containers older than a cutoff, returning pruned IDs and space freed.
import json
from datetime import datetime, timedelta
def parse_docker_ps(json_output: str, older_than_hours: int = 24) -> list:
containers = json.loads(json_output)
cutoff = datetime.now() - timedelta(hours=older_than_hours)
return [
c for c in containers
if datetime.fromisoformat(c["crea…
How to Hash Duplicate Photos and Delete Copies in Python
This script hashes image files in a directory using SHA-256 and deletes duplicate copies while keeping the first occurrence, ideal for cleaning up photo libraries.
from pathlib import Path
import hashlib
def file_hash(path, chunk_size=8192):
hasher = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(chunk_size), b""):
hasher.update(chunk)
return hasher.hexdigest()
def delete_duplicate_photos(directory):
directory …
How to Scan Files Against a Malware Hash List in Python
Compare a file's SHA-256 hash against a known malware hash set and report whether it's clean or infected.
import hashlib
from pathlib import Path
# Mock file content (in real usage, read from disk)
MOCK_FILE_CONTENT = b"print('hello world')"
KNOWN_MALWARE_HASHES = {
"8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92",
"5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8",
}
def sha25…
Post a message to a Slack webhook in Python
Send a message to a Slack webhook endpoint using the standard library's urllib.request, handling the POST request and response cleanly.
import json
from urllib import request
def post_to_slack(webhook_url: str, message: str) -> dict:
payload = json.dumps({"text": message}).encode("utf-8")
req = request.Request(
webhook_url,
data=payload,
headers={"Content-Type": "application/json"},
method="POST",
)
wit…
Build a Python Utility That Detects Duplicate Records Across Multiple Excel Sheets
A Python utility that uses pandas to find overlapping records across different Excel sheets based on specified key columns.
import pandas as pd
from pathlib import Path
def find_duplicate_records_across_sheets(file_path: str, key_columns: list, sheet_names: list) -> dict:
"""
Detect duplicate records across multiple Excel sheets based on specified key columns.
Args:
file_path: Path to the Excel file
key_co…
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.