Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
Benchmark list append vs comprehension in Python
This micro-benchmark compares the speed of building a list with a for loop and append versus a list comprehension, using the timeit module to get precise timings.
import timeit
# Build a list of the first 1,000,000 integers using append in a loop
def append_loop(n=1_000_000):
result = []
for i in range(n):
result.append(i)
return result
# Build the same list using a list comprehension
def comprehension(n=1_000_000):
return [i for i in range(n)]
if __n…
How to Build a Simple Decorator That Logs Function Calls in Python
This code shows how to create a reusable decorator that logs each function call, including arguments, return value, and execution time.
import functools
import time
def log_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__} with args={args}, kwargs={kwargs}")
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} return…
How to Create a Timing Decorator in Python
A Python decorator that measures and prints the execution time of any function using time.perf_counter.
import time
from functools import wraps
def timing_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
end = time.perf_counter()
elapsed = end - start
print(f"{func.__name__} took {elapsed:.6f} seconds"…
How to Build a Simple Debug Timer in Python
Create a context manager class to time the execution of a code block with a one-line printout.
import time
class DebugTimer:
"""Context manager that times the execution of a code block."""
def __init__(self, label="Operation"):
self.label = label
self.start_time = None
def __enter__(self):
self.start_time = time.perf_counter()
return self
def __exit__(self, e…
How to Write a Fast Smoke Test for a Critical Path in Python
A quick smoke test that validates the /health critical path executes fast enough, raising errors on wrong paths or slow responses.
import time
def smoke_test(path):
if path != "/health":
raise ValueError("Critical path expected /health")
start = time.perf_counter()
# Simulate the critical health check work
time.sleep(0.01)
elapsed = time.perf_counter() - start
if elapsed > 0.05:
raise RuntimeError("Health …
How to Mock a Metrics Decorator in Python with unittest.mock
This code demonstrates a timing decorator that wraps a function to measure execution time and prints the duration, with a unit test using unittest.mock to patch the print function and assert it was called.
import time
from functools import wraps
from unittest.mock import patch
def add_metrics(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
elapsed = time.perf_counter() - start
print(f"{func.__name__} took {elapsed:.6f}s…
Database indexing and query timing optimization in Python
Create SQLite indexes and time query performance to measure speedup for large table lookups in Python.
import sqlite3
import time
def time_query(db_path, query, params=()):
conn = sqlite3.connect(db_path)
conn.execute("PRAGMA journal_mode = WAL")
start = time.perf_counter()
result = conn.execute(query, params).fetchall()
elapsed = time.perf_counter() - start
conn.close()
return result, ela…
How to Salt Passwords per User in Python
Hash each user's password with a unique random salt using hashlib, and verify logins with timing-safe comparison.
import hashlib
import secrets
def hash_password(password: str, salt: str | None = None) -> tuple[str, str]:
"""Hash a password with a random salt (or provided salt).
Returns:
(salt_hex, password_hash_hex)
"""
if salt is None:
salt = secrets.token_hex(16)
salted = (salt + password)…
How to Verify Passwords in Constant Time in Python
Use hmac.compare_digest to verify passwords in constant time, preventing timing attacks that could reveal password length or character positions.
import hmac
import time
# Mock of a constant-time password comparison (prevents timing attacks)
def verify_password(stored_password: str, supplied_password: str) -> bool:
# hmac.compare_digest runs in constant time (for a given length)
return hmac.compare_digest(stored_password.encode(), supplied_password.enc…
How to Implement a Manual Approval Gate Mock in Python
Simulates a manual approval workflow with threshold-based rules, random decisions for medium amounts, and logs each result with timing.
import random
import time
def approve_request(amount: float) -> bool:
if amount <= 1000:
return True
if amount <= 5000:
return random.random() < 0.7
return False
def main():
requests = [500, 1200, 7500, 3000, 50]
for amount in requests:
start = time.perf_counter()
…
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.