Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
Check Invertible Mapping for Duplicate Values in Python
Detect duplicate values among (key, value) pairs to ensure the mapping is invertible, using a dictionary for O(1) lookups.
def invertible_after_dedup(pairs):
"""
Check whether a set of (key, value) pairs is invertible,
i.e., no duplicate values exist for different keys.
"""
seen = {}
for key, value in pairs:
if value in seen and seen[value] != key:
return False, f"Duplicate value '{value}' for k…
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…
Find Longest Consecutive Sequence in Python
Find the length of the longest consecutive elements sequence in an unsorted array using a set for O(n) lookups.
def longest_consecutive_length(nums):
num_set = set(nums)
longest = 0
for num in num_set:
if num - 1 not in num_set:
current = num
current_streak = 1
while current + 1 in num_set:
current += 1
current_streak += 1
…
Merge Data with Comprehension and Generator in Python
Merge user and order data using a dictionary comprehension for lookups and a generator expression to filter and transform orders.
def merge_data(users, orders):
"""
Merge user and order data using a dictionary comprehension
and a generator expression for filtering.
"""
# Build a lookup: user_id -> user name
user_map = {user["id"]: user["name"] for user in users}
# Generator: yield orders with user names attached
…
How to Build a Mock Route53 DNS API in Python
Create a mock DNS API server in Python that simulates Route53 record lookups and updates using the standard library.
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse, parse_qs
class DNSUpdateHandler(BaseHTTPRequestHandler):
records = {"example.com": "1.2.3.4"}
def do_GET(self):
domain = parse_qs(urlparse(self.path).query).get("domain", [""])[0]
if dom…
How to Mock a GraphQL Query Type in Python
Create a lightweight mock of a GraphQL Query type to simulate repository lookups without a server.
import json
class Query:
def __init__(self):
self.starred_repos = [
{"id": 1, "name": "graphql", "owner": "graphql"}
]
def repository(self, name):
if name == "graphql":
return {"id": 1, "name": "graphql", "stargazerCount": 85000}
return None
if __name…
Dedupe processed message IDs in Python
Filters an inbox of messages by removing items whose IDs have already been processed, using a set for fast lookups.
from pathlib import Path
import json
def dedupe_processed_ids(inbox_file: Path, processed_file: Path) -> list:
processed = set(json.loads(processed_file.read_text()))
inbox = json.loads(inbox_file.read_text())
deduped = [item for item in inbox if item["id"] not in processed]
return deduped
if __nam…
How to Build a Bloom Filter to Reduce Cache Misses in Python
Implement a probabilistic Bloom filter in Python that lets a cache quickly determine which keys are definitely not present, reducing expensive source lookups on cache misses.
import hashlib
import random
class BloomFilter:
def __init__(self, size=100, num_hashes=3):
self.size = size
self.num_hashes = num_hashes
self.bit_array = [0] * size
def _hashes(self, item):
result = []
for i in range(self.num_hashes):
hash_value = int(hash…
How to Implement a Negative Cache with TTL in Python
This code provides a TTL mock cache that stores negative results (cache misses) for a short time to reduce repeated lookups of missing keys.
from time import time, sleep
class TTLMockCache:
def __init__(self, ttl_seconds=5):
self.ttl = ttl_seconds
self.store = {}
self.negative_cache = {}
def get(self, key):
now = time()
if key in self.store:
value, expires_at = self.store[key]
if exp…
Simple Redis Cache Helper in Python
Build a minimal Redis-backed cache with TTL, JSON serialization, and automated fetching to speed up repeated expensive lookups.
import time
import redis
import json
class SimpleCache:
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 get(self, key):
value = self.client.get(key)…
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 Speed Up Column Lookups with DataFrame Index in Python
Use pandas set_index to make repeated column value lookups O(1)-style fast instead of scanning the whole DataFrame each time.
import pandas as pd
# Mock dataset with duplicate customer IDs
data = {"customer_id": [101, 102, 103, 101, 104, 102],
"order_amount": [250.0, 85.5, 300.0, 175.25, 420.0, 95.75]}
df = pd.DataFrame(data)
df = df.set_index("customer_id")
# Simulated lookup request
search_id = 102
# Fast index-based lookup (no…
How to implement OCSP stapling mock in Python
Simulate OCSP stapling with a caching mechanism that mocks certificate status lookups for TLS handshake validation.
import hashlib
import time
class OCSPStapler:
def __init__(self, cert_serial: str, issuer_hash: str):
self.cert_serial = cert_serial
self.issuer_hash = issuer_hash
self.cache = {}
def _mock_query_ocsp(self, serial: str) -> dict:
"""Simulate OCSP responder lookup."""
di…
How to mock DNS CAA record lookups in Python
Parse and filter DNS CAA records with a mock lookup function, demonstrating how certificate authorities validate domain authorization.
import dnslib
def parse_caa_record(record_string):
"""Parse a DNS CAA record string into its components."""
parts = record_string.split()
flags = int(parts[0])
tag = parts[1]
value = parts[2]
return flags, tag, value
def mock_caa_lookup(domain, caa_records):
"""Mock DNS CAA lookup that re…
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.