Reference library

Python Code Samples

Easy snippets you can copy, study, and run in the browser editor.

29 matches
OOP & classes easy

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.

queue deque data-structures
Python
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()
    …
13 0 Open
Algorithms & data structures easy

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.

graph bfs queue
Python
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…
14 0 Open
Algorithms & data structures easy

How to Heapify a List into a Min Heap with heapq in Python

Convert any list into a valid min heap in-place using Python's heapq.heapify(), then pop the smallest element to verify heap order.

heapq min heap heapify
Python
import heapq

data = [5, 3, 8, 1, 9, 2, 7, 4, 6]
print("Original list:", data)

heapq.heapify(data)
print("Min heap:", data)

popped = heapq.heappop(data)
print("Smallest element popped:", popped)
print("Heap after pop:", data)
14 0 Open
Algorithms & data structures easy

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.

deque sliding-window streaming
Python
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…
12 0 Open
Algorithms & data structures easy

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.

deque recents sliding-window
Python
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…
11 0 Open
Algorithms & data structures easy

Implement Queue Using Two Stacks in Python

Python class that implements a FIFO queue using two stacks, with enqueue, dequeue, peek, and emptiness checks.

queue stack data-structures
Python
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())
  …
13 0 Open
Automation & scripting easy

Schedule Daily Task in Python

Use the schedule library to queue a daily task at a fixed time, then simulate a loop that checks for pending jobs.

schedule cron timers
Python
import schedule
import time
from datetime import datetime

def daily_task():
    print(f"Task executed at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")

schedule.every().day.at("10:30").do(daily_task)

if __name__ == "__main__":
    for _ in range(3):
        schedule.run_pending()
        time.sleep(1)
12 0 Open
Data pipelines & processing easy

Fan Out Records to Multiple Sinks in Python

Distribute the same records across multiple target sinks (database, API, queue, etc.) using a defaultdict-based fan-out pattern.

fan-out defaultdict records
Python
import json
from collections import defaultdict

SINKS = ["database", "api", "message_queue", "data_lake", "monitoring"]

def fan_out(records, *sinks):
    dist = defaultdict(list)
    for record in records:
        for sink in sinks:
            dist[sink].append(record)
    return dict(dist)

if __name__ == "__main_…
12 0 Open
Data pipelines & processing easy

How to List Failed Records in a Dead Letter Queue Mock in Python

A mock Dead Letter Queue stores failed processing records with error details and timestamps, lists them, and exports to JSON.

dead-letter-queue json logging
Python
import json
from datetime import datetime, timedelta
import random


class DeadLetterQueue:
    def __init__(self):
        self.failed_records = []

    def add_failed_record(self, record_id, payload, error_message):
        self.failed_records.append({
            "record_id": record_id,
            "payload": paylo…
13 0 Open
Cloud + Python easy

How to Mock Azure Service Bus Queue in Python

A lightweight in-memory mock of the Azure Service Bus queue API for local testing without cloud dependencies.

azure service-bus mock
Python
import json
import time
from collections import deque

class ServiceBusQueueMock:
    def __init__(self, queue_name):
        self.queue_name = queue_name
        self._messages = deque()
        self._dead_letter_queue = deque()
        self._message_counter = 0

    def send_message(self, body, message_id=None, prop…
14 0 Open
Concurrency & performance easy

Thread-Safe Producer Consumer Queue in Python

A producer-consumer pattern using thread-safe queue.Queue with two threads, demonstrating safe communication and synchronized task completion.

queue threading producer-consumer
Python
import queue
import threading
import time
import random


def producer(q, item_count):
    for i in range(item_count):
        item = random.randint(1, 100)
        q.put(item)
        print(f"Producer added: {item}")
        time.sleep(0.1)


def consumer(q):
    while True:
        try:
            item = q.get(time…
12 0 Open
Streaming & messaging easy

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.

streaming deque dataclass
Python
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…
13 0 Open
Streaming & messaging easy

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.

dead-letter-queue messaging retry
Python
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…
15 0 Open
Streaming & messaging easy

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.

dataclasses deque mocking
Python
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…
14 0 Open
Streaming & messaging easy

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.

queue deque streaming
Python
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)
     …
13 0 Open
Streaming & messaging easy

How to Implement a Priority Queue for Messages in Python

Build a message priority queue with heapq and dataclasses that pops messages by priority, using sequence numbers to keep insertion order.

priority-queue heapq dataclass
Python
import heapq
from dataclasses import dataclass, field
from typing import Any

@dataclass(order=True)
class Message:
    priority: int
    sequence: int = field(compare=False)
    content: str = field(compare=False)

class PriorityQueue:
    def __init__(self):
        self._heap = []

    def push(self, priority: int,…
15 0 Open
Streaming & messaging easy

How to Mock RabbitMQ Ack Nack Requeue in Python

A mock RabbitMQ channel and consumer that simulates ack, nack, and requeue handling for testing message processing logic without a broker.

rabbitmq testing mock
Python
import json
from collections import deque


class MockChannel:
    def __init__(self):
        self.acked = []
        self.nacked = []
        self.requeued = []

    def basic_ack(self, delivery_tag):
        self.acked.append(delivery_tag)

    def basic_nack(self, delivery_tag, requeue=False):
        self.nacked.…
15 0 Open
Streaming & messaging easy

How to mock RabbitMQ queue binding with routing keys in Python

A mock demonstration of binding a queue to an exchange with multiple routing keys in RabbitMQ using Python and pika, without a real broker connection.

rabbitmq messaging pika
Python
import pika
import sys


def bind_queue_with_routing(channel, queue_name, exchange_name, routing_keys):
    """
    Mock RabbitMQ queue binding with routing keys.
    Prints the binding configuration instead of connecting to a real broker.
    """
    for routing_key in routing_keys:
        binding = {
            "q…
14 0 Open
Streaming & messaging easy

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.

queue deque fifo
Python
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.")
    …
14 0 Open
Streaming & messaging easy

Mock NATS queue group load balancing in Python

Simulates a NATS queue group where each message is delivered to exactly one subscriber using random selection with a lightweight mock.

nats queue-group messaging
Python
import random
import time
from collections import defaultdict


class MockQueueGroup:
    """Mock a NATS queue group: each message is delivered to exactly one subscriber."""

    def __init__(self, subscribers):
        self.subscribers = subscribers

    def publish(self, message):
        receiver = random.choice(se…
13 0 Open
Caching & Redis easy

Redis LPUSH RPOP List Queue Mock in Python

Implements a FIFO queue using Redis lists with LPUSH and RPOP commands, simulating task processing in Python.

redis queue fifo
Python
import redis
import time

r = redis.Redis(host='localhost', port=6379, db=0)
queue_key = 'task_queue'

# Push tasks onto the left side (LPUSH)
r.lpush(queue_key, 'task1')
r.lpush(queue_key, 'task2')
r.lpush(queue_key, 'task3')

# Mock processing: pop from the right side (RPOP) — FIFO order
while r.llen(queue_key) > 0:…
13 0 Open
Reliability & rate limiting easy

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.

rate-limiting decorator time
Python
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…
13 0 Open
Reliability & rate limiting easy

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.

admission-control queue rate-limiting
Python
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…
16 0 Open
Reliability & rate limiting easy

Exactly Once Processing Dedupe Mock in Python

Implements a streaming deduplicator using a set and queue to guarantee each item is processed exactly once while preserving insertion order.

deduplication exactly-once streaming
Python
from collections import deque

class DedupeStream:
    def __init__(self):
        self.seen = set()
        self.queue = deque()

    def add(self, item):
        if item not in self.seen:
            self.seen.add(item)
            self.queue.append(item)
            print(f"Processed: {item} (exactly once)")
      …
15 0 Open

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

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. 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.