Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Translate Characters in a String with str.maketrans in Python
Build and apply character translation tables with str.maketrans and str.translate to replace, delete, or remap letters in a Python string.
def translate_demo():
# Build a translation table: a→1, e→2, i→3, o→4, u→5
table = str.maketrans("aeiou", "12345")
text = "Hello, Python world! Keep coding, friend."
translated = text.translate(table)
print(f"Original: {text}")
print(f"Translated: {translated}")
# Example wit…
Build a Python Script That Detects and Deletes Empty Files Across Folders
A Python script that recursively finds and removes all zero-byte files across nested directories, returning a list of deleted paths.
import os
from pathlib import Path
def find_and_delete_empty_files(root_dir: str) -> list:
"""Find and delete all empty files under root_dir. Returns list of deleted paths."""
deleted = []
for file_path in Path(root_dir).rglob('*'):
if file_path.is_file() and file_path.stat().st_size == 0:
…
How to Delete a File if it Exists in Python
Delete a file safely in Python using pathlib's Path.unlink, checking existence first to avoid errors.
from pathlib import Path
def delete_file_if_exists(file_path: str) -> bool:
"""Delete a file if it exists. Returns True if deleted, False if not found."""
path = Path(file_path)
if path.exists():
path.unlink()
print(f"Deleted: {path}")
return True
else:
print(f"File not…
How to Build a Two-Way Dictionary in Python
Implement a BiDict class that supports both forward key-to-value and reverse value-to-key lookups with a simple add, delete, and update API.
class BiDict:
def __init__(self, data=None):
self.forward = {}
self.backward = {}
if data:
self.update(data)
def update(self, data):
for key, value in data.items():
self[key] = value
def __setitem__(self, key, value):
self.forward[key] = val…
How to Build an In-Memory CRUD Repository Class in Python
Define a Python Repository class that stores objects in a dictionary and supports create, read, update, delete, and list operations.
class Repository:
def __init__(self):
self._data = {}
def create(self, key, value):
self._data[key] = value
return key
def read(self, key):
return self._data.get(key)
def update(self, key, value):
if key not in self._data:
raise KeyError(f"Key '{ke…
Implement Insert Delete GetRandom O(1) in Python
Build a RandomizedSet class that supports insert, delete, and get_random in average O(1) time using a list and a dictionary mapping values to indices.
import random
class RandomizedSet:
def __init__(self):
self.values = []
self.index_map = {}
def insert(self, val):
if val in self.index_map:
return False
self.index_map[val] = len(self.values)
self.values.append(val)
return True
def delete(self…
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"),
…
Find and Delete Duplicate Files Using Hashing in Python
Walk a directory tree, compute SHA256 hashes for every file, and delete duplicates that share the same hash.
import hashlib
import os
from pathlib import Path
def file_hash(path, block_size=65536):
"""Return SHA256 hash of file content."""
hasher = hashlib.sha256()
with open(path, 'rb') as f:
while chunk := f.read(block_size):
hasher.update(chunk)
return hasher.hexdigest()
def find_and_d…
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 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 Recover Deleted .txt Files from a Backup in Python
A Python function that searches a backup directory recursively and copies all .txt files to a destination folder, printing each recovered file name and a total count.
import os
import shutil
from pathlib import Path
def recover_deleted_txt_files(source_backup_dir: str, destination_dir: str) -> None:
"""Recover .txt files from backup directory."""
backup_path = Path(source_backup_dir)
dest_path = Path(destination_dir)
dest_path.mkdir(parents=True, exist_ok=True)
…
Generate a Mock CDC Changelog in Python
Simulate a CDC changelog with INSERT, UPDATE, and DELETE operations, timestamps, and record snapshots for testing data pipelines.
import json
from datetime import datetime, timedelta
def generate_mock_changelog(records, operations=("INSERT", "UPDATE", "DELETE")):
"""Simulate a CDC changelog from a list of record snapshots."""
base_time = datetime(2025, 1, 1, 8, 0, 0)
changelog = []
for idx, record in enumerate(records):
…
How to Stage All Modified Files with git add -u in Python
Runs git add -u from Python to stage all modified and deleted tracked files, then prints the short status.
import subprocess
def stage_all_modified_files(repo_path="."):
"""Run git add -u to stage all modified and deleted tracked files."""
result = subprocess.run(
["git", "add", "-u"],
cwd=repo_path,
capture_output=True,
text=True,
)
if result.returncode != 0:
print…
How to Mock AWS SQS Send Receive Delete in Python
Build an in-memory mock of the SQS send, receive, and delete message flow for local testing.
import json
from collections import deque
from uuid import uuid4
class MockSQSQueue:
def __init__(self, name):
self.name = name
self._messages = deque()
self._in_flight = {}
def send_message(self, body, attributes=None):
message_id = str(uuid4())
message = {
…
How to Test Environment Variables with pytest monkeypatch in Python
Shows how to use pytest's monkeypatch fixture to set and delete environment variables for isolated tests.
import os
import pytest
def get_database_url():
return os.getenv("DATABASE_URL", "postgres://default")
def test_database_url_with_env(monkeypatch):
monkeypatch.setenv("DATABASE_URL", "postgres://test-db")
assert get_database_url() == "postgres://test-db"
def test_database_url_default(monkeypatch):
m…
How to Implement the Repository Pattern in Python with an In-Memory Dict
Stores, retrieves, updates, and deletes user records in memory using a Repository abstraction over a plain dict, isolating data access from business logic.
class UserRepository:
def __init__(self):
self._storage = {}
self._next_id = 1
def create(self, name, email):
user_id = self._next_id
self._next_id += 1
self._storage[user_id] = {"id": user_id, "name": name, "email": email}
return self._storage[user_id]
def…
How to Implement a REST DELETE Mock Server Returning 204 in Python
A minimal HTTP server mock that responds to DELETE requests with 204, 404, or 403 statuses based on the resource ID.
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
class MockHandler(BaseHTTPRequestHandler):
def do_DELETE(self):
if self.path.startswith("/api/resource/"):
resource_id = self.path.split("/")[-1]
if resource_id == "42":
# Successful delete: 204 …
Implement a retry queue with visibility timeout in Python
This code simulates a message queue with a visibility timeout, allowing messages to be retried if not deleted before the timeout expires.
import time
from collections import deque
class SimpleQueue:
def __init__(self, visibility_timeout=2):
self.queue = deque()
self.in_flight = {}
self.visibility_timeout = visibility_timeout
def send(self, message):
self.queue.append(message)
def receive(self):
if …
How to Mock Redis Pipeline Batch Commands in Python
Create a lightweight MockRedis class that simulates Redis pipeline batching with SET, GET, and DELETE operations for testing without a live server.
import redis
import time
class MockRedis:
def __init__(self):
self.data = {}
def pipeline(self):
return MockPipeline(self)
def execute(self, commands):
results = []
for cmd in commands:
op, args = cmd[0], cmd[1:]
if op == "SET":
se…
How to Mock a Redis Session Store Cookie SID in Python
Mock a Redis-backed session store with a cookie-based session ID (SID) in Python, including the create, read, and delete operations.
import redis
import uuid
import time
class RedisSessionStore:
def __init__(self, host="localhost", port=6379, db=0, prefix="session:"):
self.client = redis.Redis(host=host, port=port, db=db)
self.prefix = prefix
def create_session(self, timeout_seconds=3600):
session_id = uuid.uuid4(…
How to Use Redis as a Cache in Python
A beginner-friendly RedisCache helper that stores, retrieves, and deletes JSON values with automatic TTL expiration using the redis-py client.
import json
import time
import redis
class RedisCache:
def __init__(self, host="localhost", port=6379, db=0, default_ttl=60):
self.client = redis.Redis(host=host, port=port, db=db, decode_responses=True)
self.default_ttl = default_ttl
def set(self, key, value, ttl=None):
"""Store a v…
How to Mock a Baggage Context (Key-Value Store) in Python
This code implements an in-memory key-value mock of a baggage context, letting you set, get, check, and delete keys for tracing-style metadata.
class BaggageContext:
def __init__(self):
self._store = {}
def set(self, key, value):
self._store[key] = value
return value
def get(self, key, default=None):
return self._store.get(key, default)
def has(self, key):
return key in self._store
def delete(sel…
Simulate PostgreSQL Vacuum to Reclaim Space in Python
A Python class that safely rewrites a data file to remove deleted rows and reclaim physical space, mimicking PostgreSQL's VACUUM operation.
import shutil
import os
class VacuumCleaner:
"""Simulates PostgreSQL-style vacuum reclaiming dead space in a file."""
def __init__(self, filepath, fill_ratio=0.7, dead_marker="[DELETED]"):
self.filepath = filepath
self.fill_ratio = fill_ratio
self.dead_marker = dead_marker
…
How to Mock a Redis Session Store in Python
An in-memory RedisSessionStore class with TTL-based expiry, get/set/delete/exists methods, and JSON field support—perfect for testing and prototyping without a live Redis.
import time
import json
from collections import defaultdict
class RedisSessionStore:
"""In-memory mock of a Redis-backed session store."""
def __init__(self, ttl=3600):
self._data = defaultdict(dict)
self._expires = {}
self._ttl = ttl
def set(self, session_id, field, value):
…
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.