Python Code
Samples
Medium snippets you can copy, study, and run in the browser editor.
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
…
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 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…
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.