Python Code
Samples
Medium snippets you can copy, study, and run in the browser editor.
How to Create a Counter Closure in Python
Build a closure in Python that remembers and increments a counter across calls without using global variables.
def create_counter(start=0):
count = start
def increment():
nonlocal count
count += 1
return count
return increment
if __name__ == "__main__":
counter = create_counter(10)
print(counter())
print(counter())
print(counter())
How to Implement a Trampoline for Tail Recursion in Python
This code implements a trampoline decorator that converts tail-recursive functions into iterative loops, allowing deep recursion without hitting Python's recursion limit.
def trampoline(fn):
"""Convert a tail-recursive function into an iterative loop."""
def wrapper(*args, **kwargs):
result = fn(*args, **kwargs)
while callable(result):
result = result()
return result
return wrapper
@trampoline
def factorial(n, acc=1):
"""Tail-recursi…
How to Invalidate Cache When Arguments Change in Python
A memoization decorator that caches function results keyed by arguments, automatically invalidating when inputs change.
from functools import wraps
def memoize(func):
cache = {}
@wraps(func)
def wrapper(*args, **kwargs):
key = (args, tuple(sorted(kwargs.items())))
if key not in cache:
cache[key] = func(*args, **kwargs)
return cache[key]
return wrapper
@memoize
def expensiv…
Collect Multiple Validation Errors in Python Before Raising
A chainable Validator class that accumulates all validation errors and raises them together in a single exception.
class ValidationError(Exception):
pass
class Validator:
def __init__(self):
self.errors = []
def validate_required(self, value, field_name):
if not value:
self.errors.append(f"{field_name} is required")
return self
def validate_email(self, email):
…
Implement circuit breaker open after failures demo in Python
A minimal CircuitBreaker class that calls a function and automatically 'opens' after a set number of consecutive failures, blocking further calls with a RuntimeError.
import time
from datetime import datetime
class CircuitBreaker:
def __init__(self, threshold=3):
self.threshold = threshold
self.failure_count = 0
self.is_open = False
def call(self, func, *args, **kwargs):
if self.is_open:
raise RuntimeError("Circuit is OPEN")
…
Create a Local File Versioning System Using Pure Python
Track file changes locally by copying versions with SHA-256 hashes and JSON metadata using only the Python standard library.
import os
import shutil
import hashlib
import json
import time
from pathlib import Path
class LocalFileVersioning:
def __init__(self, target_dir="versioned_files", versions_dir="versions"):
self.target_dir = Path(target_dir)
self.versions_dir = Path(versions_dir)
self.metadata_file = self.…
Create a ZIP Archive of a Folder in Python
Recursively zip all files in a folder into a single archive using the standard library zipfile and pathlib modules.
import zipfile
from pathlib import Path
def zip_folder(source_dir: str, archive_path: str) -> None:
"""Zip all files in source_dir recursively into archive_path."""
source = Path(source_dir)
with zipfile.ZipFile(archive_path, "w", zipfile.ZIP_DEFLATED) as archive:
for file_path in source.rglob("*"…
How to Atomically Write Files in Python with Temp File and Rename
Write a file atomically using a temporary file and os.replace so readers never see partial writes even if the process crashes mid-write.
import os
import tempfile
from pathlib import Path
def atomic_write(path: str | Path, content: str) -> None:
"""Write content to path atomically using a temp file and rename."""
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
fd, temp_path = tempfile.mkstemp(
dir=str(path.par…
How to Automatically Extract Every Archive in a Folder with Python
Walk through a folder and extract all ZIP, RAR, and 7Z archives into separate subdirectories using Python.
import zipfile
import rarfile
import py7zr
import pathlib
def extract_archives(folder: str):
"""Extract every ZIP, RAR, and 7Z archive in the given folder."""
folder_path = pathlib.Path(folder)
for archive_file in folder_path.iterdir():
suffix = archive_file.suffix.lower()
try:
…
How to Automatically Merge Hundreds of Excel Files Without Losing Formatting in Python
Merge all .xlsx files in a folder into a single Excel workbook, preserving individual sheet structures with sheet name prefixes.
import pandas as pd
from pathlib import Path
def merge_excel_files(folder_path: str, output_path: str) -> None:
"""
Merge all .xlsx files in a folder into a single Excel file,
preserving individual sheet structures.
"""
folder = Path(folder_path)
excel_files = list(folder.glob("*.xlsx"))
…
How to Generate an Inventory Report of All Files in Python
Walk a directory tree, collect metadata for every file, and write a CSV inventory report using Python's os, pathlib, and csv modules.
import os
import csv
from pathlib import Path
from datetime import datetime
def generate_inventory_report(root_dir: str = "/", output_file: str = "inventory_report.csv"):
headers = ["File Path", "Size (bytes)", "Last Modified", "File Type"]
rows = []
start_time = datetime.now()
for dirpath, dirna…
How to Load Pickle Files Safely in Python
This code demonstrates how to load pickle files safely in Python by using a restricted unpickler that only allows specific, trusted classes, preventing arbitrary code execution from untrusted pickles.
import pickle
# Default pickle.load is unsafe: it executes arbitrary code when unpickling.
class Unsafe:
def __reduce__(self):
return (eval, ("open('/tmp/pickle_demo.txt', 'w').write('pwned')",))
# Create a malicious payload (simulating untrusted source)
malicious_data = pickle.dumps(Unsafe())
# Safe ap…
How to Write a List of Lines to a Text File Safely in Python
This code atomically writes a list of strings as lines to a text file using a temporary file and os.replace to prevent corruption.
from pathlib import Path
import tempfile
import os
def write_lines_safely(lines: list[str], filepath: str | Path) -> None:
"""Write lines to a text file atomically to avoid corruption."""
path = Path(filepath)
path.parent.mkdir(parents=True, exist_ok=True)
fd, temp_path = tempfile.mkstemp(dir=str…
Find All Leaf Paths in a Nested Dict in Python
Recursively traverse a nested dictionary and yield every leaf path as a list of keys, including paths to empty dictionaries.
def find_leaf_paths(data, path=None):
if path is None:
path = []
if not isinstance(data, dict) or not data:
yield path
return
for key, value in data.items():
yield from find_leaf_paths(value, path + [key])
if __name__ == "__main__":
nested = {
"a": 1,
…
How to Build a TTL Cache Dict in Python
Create a dictionary subclass that automatically expires keys after a fixed time-to-live using timestamps.
import time
class TTLDict(dict):
def __init__(self, ttl, *args, **kwargs):
self.ttl = ttl
self._expires = {}
super().__init__(*args, **kwargs)
def __setitem__(self, key, value):
super().__setitem__(key, value)
self._expires[key] = time.time() + self.ttl
def __geti…
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 Implement the State Pattern in Python
Implement the State design pattern in Python by delegating behavior to state objects, letting a media player change actions dynamically without if-else chains.
class State:
def play(self, player): pass
def pause(self, player): pass
def stop(self, player): pass
class PlayingState(State):
def play(self, player):
return "Already playing"
def pause(self, player):
player.state = PausedState()
return "Pausing playback"
def stop(self…
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…
Understanding Multiple Inheritance Method Resolution Order in Python
This code demonstrates how Python's MRO determines which greet method is called in a diamond inheritance scenario, and prints the full MRO for class D.
class A:
def greet(self):
return "Hello from A"
class B(A):
def greet(self):
return "Hello from B"
class C(A):
def greet(self):
return "Hello from C"
class D(B, C):
pass
if __name__ == "__main__":
d = D()
print(d.greet())
print(D.__mro__)
Binary Search for Ship Capacity in Python
Use binary search to find the minimum ship capacity that can transport all packages within a given number of days.
def ship_within_days(weights, days):
def can_ship(capacity):
current = 0
needed_days = 1
for weight in weights:
if current + weight > capacity:
needed_days += 1
current = 0
current += weight
return needed_days <= days
low …
Binary Search on Answer in Python: Koko Eating Bananas
Find the minimum eating speed so Koko finishes all banana piles within a given hour limit using binary search on the answer.
import math
def min_eating_speed(piles, h):
"""Return minimum integer eating speed K so Koko finishes within h hours."""
def hours_needed(speed):
return sum(math.ceil(p / speed) for p in piles)
low, high = 1, max(piles)
while low < high:
mid = (low + high) // 2
if hours_needed…
Find All Triplets with Sum Zero in Python
This code finds all unique triplets in an array that sum to zero using a sorted array and two-pointer technique.
def find_triplets(nums):
nums.sort()
n = len(nums)
triplets = []
for i in range(n - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
left, right = i + 1, n - 1
while left < right:
total = nums[i] + nums[left] + nums[right]
if total == 0:
…
How to Find Four Sum Quadruplets in Python (Sorted Demo)
Find all unique quadruplets in a sorted array that sum to a target, with duplicate skipping.
def four_sum(nums, target):
nums.sort()
result = []
n = len(nums)
for i in range(n - 3):
if i > 0 and nums[i] == nums[i - 1]:
continue
for j in range(i + 1, n - 2):
if j > i + 1 and nums[j] == nums[j - 1]:
continue
left, right = j + 1…
How to Find Intersection of Two Sorted Interval Lists in Python
A two-pointer algorithm that finds all overlapping intervals between two sorted lists of intervals.
def interval_intersection(list1, list2):
i = j = 0
result = []
while i < len(list1) and j < len(list2):
# Find the overlap between current intervals
lo = max(list1[i][0], list2[j][0])
hi = min(list1[i][1], list2[j][1])
# If there's an overlap, add it to result
…
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.