Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
How to Record Last N Errors with a Ring Buffer in Python
Use collections.deque with maxlen to keep only the most recent N error messages while discarding older entries automatically.
import collections
class ErrorRecorder:
def __init__(self, size):
self.buffer = collections.deque(maxlen=size)
def record_error(self, message):
self.buffer.append(message)
def get_errors(self):
return list(self.buffer)
if __name__ == "__main__":
recorder = ErrorRecorder(3)
…
How to Implement a Queue Class in Python Using deque
Build a FIFO queue class in Python backed by the collections.deque container with enqueue, dequeue, peek, and size methods.
from collections import deque
class Queue:
def __init__(self):
self._items = deque()
def enqueue(self, item):
self._items.append(item)
def dequeue(self):
if self.is_empty():
raise IndexError("dequeue from empty queue")
return self._items.popleft()
…
How to Get the Breadth-First Traversal Order of a Graph in Python
Performs a breadth-first search on an adjacency list and returns the order nodes are visited, using a deque for efficient queue operations.
from collections import deque
def bfs_order(adjacency, start=0):
"""Return the order nodes are visited in a breadth-first traversal."""
visited = set()
order = []
queue = deque([start])
visited.add(start)
while queue:
node = queue.popleft()
order.append(node)
for neig…
How to Implement a Moving Average from a Data Stream in Python
Implement a MovingAverage class using a deque and running sum to compute the average of the last k values from a continuous data stream.
from collections import deque
class MovingAverage:
def __init__(self, size):
self.size = size
self.queue = deque()
self.window_sum = 0
def next(self, val):
self.queue.append(val)
self.window_sum += val
if len(self.queue) > self.size:
self.window_su…
How to Implement a Recent Counter with a Deque in Python
Implements a RecentCounter class that uses a deque to count ping requests within the last 3000 milliseconds.
from collections import deque
import time
class RecentCounter:
def __init__(self):
self.hits = deque()
def ping(self, t: int) -> int:
self.hits.append(t)
while self.hits and self.hits[0] < t - 3000:
self.hits.popleft()
return len(self.hits)
if __name__ == "__mai…
Implement Queue Using Two Stacks in Python
Python class that implements a FIFO queue using two stacks, with enqueue, dequeue, peek, and emptiness checks.
class QueueUsingStacks:
def __init__(self):
self.stack_in = []
self.stack_out = []
def enqueue(self, value):
self.stack_in.append(value)
def dequeue(self):
if not self.stack_out:
while self.stack_in:
self.stack_out.append(self.stack_in.pop())
…
How to Keep Last K Turns in a Memory Buffer in Python
A TurnBuffer class using deque with maxlen to keep only the most recent k conversation turns in memory for LLM context.
from collections import deque
class TurnBuffer:
def __init__(self, k):
self.k = k
self.turns = deque(maxlen=k)
def add(self, turn):
self.turns.append(turn)
def last_k(self):
return list(self.turns)
if __name__ == "__main__":
buffer = TurnBuffer(3)
buffer.add("tu…
How to Implement a Sliding Window Average in Python
Compute the average of the most recent N values in a stream using a bounded deque, efficiently updating the total as new values arrive.
from collections import deque
class SlidingWindowAverage:
def __init__(self, window_size):
self.window_size = window_size
self.window = deque(maxlen=window_size)
self.total = 0
def add(self, value):
if len(self.window) == self.window_size:
self.total -= self.windo…
Build a Streaming Messaging Helper in Python
Create a simple message stream class that stores recent messages, sends user messages, and retrieves history or latest messages with timestamps.
from collections import deque
from dataclasses import dataclass
from datetime import datetime
import time
@dataclass
class Message:
user: str
text: str
timestamp: str = ""
def __post_init__(self):
if not self.timestamp:
self.timestamp = datetime.now().strftime("%H:%M:%S")
class…
Dead Letter Queue Failed Messages List Mock in Python
Implements a simple in-memory dead letter queue to collect, list, and retry failed messages, with JSON serialization for inspection in streaming pipelines.
import json
from collections import deque
class Message:
def __init__(self, message_id, payload, attempts=0):
self.message_id = message_id
self.payload = payload
self.attempts = attempts
def __repr__(self):
return f"Message(id={self.message_id}, attempts={self.attempts})"
c…
How to Build a Materialized View Updater Consumer Mock in Python
A mock consumer that queues change events and triggers refresh callbacks to simulate materialized view updates.
import time
from collections import deque
from dataclasses import dataclass, field
from typing import Callable, Deque, Optional
@dataclass
class MaterializedViewUpdater:
"""Mock updater that consumes change events and refreshes a view."""
refresh: Optional[Callable[[str], None]] = None
queue: Deque[tuple…
How to Build a Message Stream Queue in Python
A beginner-friendly MessageStream class built on deque that sends messages one at a time, tracks unread counts, and records sent items.
from collections import deque
import time
class MessageStream:
def __init__(self, messages):
self._queue = deque(messages)
self._sent = []
def send_next(self):
if not self._queue:
return None
message = self._queue.popleft()
self._sent.append(message)
…
How to Implement a Tumbling Window Counter in Python
Count events that fall within a fixed-size sliding time window using a deque and pruning logic.
from collections import deque
import time
class TumblingWindowCounter:
def __init__(self, window_size_seconds):
self.window_size = window_size_seconds
self.window = deque()
def add_event(self, timestamp):
self.window.append(timestamp)
def count(self, current_time):
while…
Implement a FIFO Message Queue in Python with deque
This code implements a FIFO (first-in-first-out) message queue class using Python's collections.deque, providing enqueue, dequeue, peek, and size operations.
from collections import deque
class MessageQueue:
def __init__(self):
self.queue = deque()
def enqueue(self, message):
self.queue.append(message)
print(f"Enqueued: {message}")
def dequeue(self):
if self.is_empty():
print("Queue is empty, cannot dequeue.")
…
Sliding Window Average with Deque in Python
Computes the running average of a sliding window over streaming numbers using a collections.deque for O(1) pop-left operations.
from collections import deque
class SlidingAverage:
def __init__(self, window_size):
self.window_size = window_size
self.window = deque()
self.total = 0
def add(self, value):
self.window.append(value)
self.total += value
if len(self.window) > self.window_size:
…
Build a Rate Limiter Decorator in Python
This code defines a reusable rate limiter decorator that caps function calls within a sliding time window using a deque and monotonic time.
import time
from collections import deque
def rate_limiter(max_calls: int, period: float):
calls = deque()
def decorator(func):
def wrapper(*args, **kwargs):
now = time.monotonic()
while calls and now - calls[0] >= period:
calls.popleft()
if len(ca…
Build a queue-based admission control system in Python
Implement a simple bounded-queue admission controller that accepts or rejects incoming requests based on current queue capacity.
from collections import deque
import time
class AdmissionControl:
"""Simple admission control using a bounded queue.
Requests arrive at the queue; they are admitted in FIFO order.
If the queue is full, the incoming request is rejected.
"""
def __init__(self, capacity: int):
self.capacit…
How to Implement a Rate Limiter in Python
A beginner-friendly Python class that tracks call timestamps with a deque to allow or block calls based on a max rate per time period.
import time
from collections import deque
class RateLimiter:
"""Simple rate limiter for beginners."""
def __init__(self, max_calls: int, period_seconds: float):
self.max_calls = max_calls
self.period = period_seconds
self.calls = deque()
def allow(self) -> bool:
"""Retur…
How to Implement a Sliding Window Counter in Python
This code implements an approximate sliding window counter using a deque of time-based buckets to track event counts within a recent time window.
from collections import deque
from time import time
class SlidingWindowCounter:
def __init__(self, window_size, bucket_size=1):
self.window_size = window_size
self.bucket_size = bucket_size
self.buckets = deque()
def _evict_expired(self, now):
while self.buckets and self.buck…
Rate Limiting with Queue Rejection in Python
Simulates a load shed pattern that rejects tasks when a queue fills up.
from collections import deque
import time
class RateLimiter:
def __init__(self, max_queue_size=3):
self.queue = deque()
self.max_queue_size = max_queue_size
self.rejected_count = 0
def submit(self, task_name):
if len(self.queue) >= self.max_queue_size:
self.reject…
How to Compute SRE Metrics Like Error Rate and Availability in Python
Tracks log events in a sliding time window and calculates error rate per second and availability percentage using an easy-to-follow class.
from collections import deque
from datetime import datetime, timedelta
from typing import Dict, Deque
class LogMetrics:
"""Simple observability helper to track log events and calculate SRE metrics."""
def __init__(self, window_seconds: int = 60):
self.window_seconds = window_seconds
self.eve…
How to Implement Tail Sampling in Python
Sample the slowest subset of calls (tail) for latency analysis using a deque with a random ratio gate.
import random
import time
from collections import deque
class TailSampler:
def __init__(self, tail_ratio=0.1, max_samples=100):
self.tail_ratio = tail_ratio
self.max_samples = max_samples
self.samples = deque(maxlen=max_samples)
self.total_calls = 0
def record(self, latency_ms…
How to Simulate a Queue Depth Gauge in Python
Simulate a queue depth over time using a random enqueue/dequeue process, returning depth values that can be used for monitoring or testing dashboards.
import collections
import random
import time
def simulate_queue_depth(max_depth=10, steps=20):
queue = collections.deque()
depth_history = []
for _ in range(steps):
# Randomly enqueue or dequeue
if random.random() < 0.6 and len(queue) < max_depth:
queue.append("task")
…
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.