Reference library

Python Code Samples

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

29 matches
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
Comprehensions & generators easy

Generate UUID4 Values with a Python Generator

This code defines a generator function that yields mock UUID4 values, allowing you to stream unique identifiers one at a time.

uuid generators streaming
Python
import uuid

def generate_uuids(count=5):
    """Generate a stream of mock UUID4 values."""
    for _ in range(count):
        yield uuid.uuid4()

if __name__ == "__main__":
    # Generate and print 5 UUIDs
    for uid in generate_uuids(5):
        print(uid)
15 0 Open
Comprehensions & generators easy

Memory efficient map over large file in Python

A generator-based streaming map that processes a large file line by line without loading the whole file into memory.

generator file-io streaming
Python
import sys

def process_lines(file_path):
    """Memory-efficient map over a large file: yields processed lines."""
    with open(file_path, 'r') as f:
        for line in f:
            # Example mapping: strip whitespace and uppercase
            yield line.strip().upper()

if __name__ == "__main__":
    # Use a sma…
12 0 Open
AI & LLM integration patterns easy

How to Accumulate Streamed Tokens into a Final String in Python

Accumulate a stream of tokens into a single final string by concatenating each token in sequence.

streaming tokens strings
Python
def accumulate_tokens(tokens):
    """Accumulate a stream of tokens into a single final string."""
    result = ""
    for token in tokens:
        result += token
    return result


if __name__ == "__main__":
    token_stream = ["Hello", ", ", "world", "!", " This ", "is ", "accumulated."]
    final_string = accumul…
16 0 Open
AI & LLM integration patterns easy

How to Stream Tokens from a Mock LLM in Python

Simulate real-time LLM streaming by yielding tokens one at a time with a delay, making it easy to test streaming UIs.

generator llm streaming
Python
import time
from typing import Generator


def stream_tokens(text: str, delay: float = 0.05) -> Generator[str, None, None]:
    """Simulate an LLM streaming tokens word by word."""
    for word in text.split():
        yield word
        time.sleep(delay)


if __name__ == "__main__":
    sample = "Hello world! This is…
15 0 Open
Data pipelines & processing easy

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.

deque sliding-window streaming
Python
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…
15 0 Open
Data pipelines & processing easy

How to Track Checkpoint Offset After Batch Commit in Python

A batch processor that tracks the last successfully committed offset after processing records in batches, advancing the checkpoint only when each batch commits successfully.

batch-processing checkpoint offset
Python
import json
from typing import Any


class BatchProcessor:
    """Tracks checkpoint offset after committing batches."""

    def __init__(self, batch_size: int = 3):
        self.batch_size = batch_size
        self.offset = 0  # last successfully committed offset (exclusive)
        self.total_committed = 0

    def …
12 0 Open
Data pipelines & processing easy

How to route late-arriving data to a side output in Python

Separate late-arriving events from a streaming data batch into a dead-letter side output list using a timestamp threshold.

data pipelines streaming dead-letter
Python
from collections import defaultdict

def late_arriving_side_output(events, late_threshold_ts):
    """
    Mock a streaming pipeline that separates late-arriving data events
    into a side output list (e.g., for dead-letter analysis).

    events: list of (timestamp, data) tuples, timestamps as ints.
    late_thresho…
12 0 Open
Concurrency & performance easy

Using a Python Generator Instead of a List to Save Memory

Compare a list approach with a generator to stream values lazily, avoiding memory-heavy storage of large sequences.

generator lazy-evaluation memory
Python
def fibonacci_generator(limit):
    a, b = 0, 1
    count = 0
    while count < limit:
        yield a
        a, b = b, a + b
        count += 1


def sum_first_n(generator, n):
    total = 0
    for i, value in enumerate(generator):
        if i >= n:
            break
        total += value
    return total


if __…
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

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.

deduplication streaming json
Python
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…
12 0 Open
Streaming & messaging easy

Event Envelope with Schema Version Field in Python

Build a typed event envelope dataclass with an explicit schema version field for mock streaming scenarios.

event dataclass messaging
Python
from dataclasses import dataclass, field
from datetime import datetime
import uuid


@dataclass
class Event:
    event_id: str = field(default_factory=lambda: str(uuid.uuid4()))
    event_type: str = "user.created"
    version: str = "1.0.0"
    created_at: str = field(default_factory=lambda: datetime.utcnow().isoform…
15 0 Open
Streaming & messaging easy

Exactly Once Idempotent Consumer Store in Python

A mock key-value store that guarantees exactly-once processing by rejecting duplicate message keys in a message or event stream.

idempotency streaming deduplication
Python
from collections import defaultdict

class ExactlyOnceStore:
    def __init__(self):
        self.processed = defaultdict(set)
        self.data = {}

    def consume(self, key, value):
        if key in self.data:
            return False
        self.data[key] = value
        return True

    def get_processed_count…
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 Build a Mock Change Data Capture Event Stream in Python

Generate a deterministic list of mock CDC events with event IDs, stream positions, payloads, and timestamps for testing streaming pipelines.

cdc mock event-stream
Python
from itertools import count
from random import choice, randint, seed
from datetime import datetime, timedelta

seed(42)  # Make output deterministic
event_types = ["INSERT", "UPDATE", "DELETE"]
table_names = ["users", "orders", "products", "payments"]
counter = count(1)

def mock_cdc_event(stream_index: int) -> dict:
…
12 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 Implement a Tumbling Window Counter in Python

Count events that fall within a fixed-size sliding time window using a deque and pruning logic.

streaming window aggregation
Python
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…
14 0 Open
Streaming & messaging easy

How to Partition and Order Kafka-Style Messages by Key in Python

Group messages with the same key into ordered buckets using hashing and a defaultdict, mimicking Kafka partition ordering.

streaming partitioning kafka-pattern
Python
from dataclasses import dataclass
from collections import defaultdict

@dataclass
class Message:
    key: str
    content: str

def partition_and_order(messages, num_partitions=3):
    partitions = defaultdict(list)
    for msg in messages:
        partition_id = hash(msg.key) % num_partitions
        partitions[parti…
14 0 Open
Streaming & messaging easy

How to Simulate a Micro-Batch Interval Trigger in Python

A dataclass-based mock that emits batch numbers at fixed intervals, mimicking a micro-batch streaming scheduler for testing and development.

streaming mock dataclass
Python
import time
from dataclasses import dataclass, field
from typing import List, Callable


@dataclass
class MicroBatchTriggerMock:
    batch_interval_seconds: float = 0.5
    max_batches: int = 5
    _batches_emitted: int = 0
    _next_emit_time: float = field(init=False, default=0)

    def start(self, on_batch: Callab…
13 0 Open
Streaming & messaging easy

How to deduplicate messages by ID in Python

Track seen message IDs in a set to skip duplicate messages and store unique content in a dict, with exact output showing which messages were added or skipped.

deduplication set messaging
Python
import time

class MessageStore:
    def __init__(self):
        self.seen_ids = set()
        self.messages = {}
    
    def add(self, message_id, content, timestamp=None):
        timestamp = timestamp or time.time()
        if message_id in self.seen_ids:
            return False
        self.seen_ids.add(message_…
12 0 Open
Streaming & messaging easy

Redis Pub/Sub Channel Subscribe Mock in Python

A lightweight in-memory mock of Redis pub/sub that lets you subscribe to channels, publish messages, and verify handler behavior in tests without a real Redis server.

redis pubsub testing
Python
class MockRedisPubSub:
    def __init__(self):
        self.channels = {}

    def subscribe(self, channel):
        if channel not in self.channels:
            self.channels[channel] = []
        return self.channels[channel]

    def publish(self, channel, message):
        if channel in self.channels:
            …
11 0 Open
Streaming & messaging easy

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.

sliding-window deque streaming
Python
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:
…
13 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.