Reference library

Python Code Samples

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

9 matches
Files & data medium

Chunk Large File Upload Simulation by Blocks in Python

A Python script reads a large binary file in fixed-size chunks and simulates a block-by-block upload with per-chunk SHA256 hashing.

file i/o chunking hashing
Python
import os
import hashlib
from pathlib import Path


def read_file_in_chunks(file_path, chunk_size=8196):
    """Yield chunks of a file as bytes."""
    with open(file_path, 'rb') as f:
        while chunk := f.read(chunk_size):
            yield chunk


def simulate_chunked_upload(file_path, chunk_size=8196):
    """S…
15 0 Open
Dictionaries & sets medium

Traverse Nested Dict Paths Depth-First in Python

Recursively walk a nested dictionary depth-first and yield each full path from root to leaf as lists.

recursion generators nested-dicts
Python
def depth_first_paths(node, path=None):
    if path is None:
        path = []
    
    if not isinstance(node, dict):
        yield path + [node]
        return
    
    for key, value in node.items():
        new_path = path + [key]
        if isinstance(value, dict):
            yield from depth_first_paths(value, …
13 0 Open
Comprehensions & generators medium

Build a Generator Pipeline in Python: Filter Then Map

Create a lazy data pipeline by chaining generator functions that read, filter, map, and write data step by step.

generators pipeline lazy-evaluation
Python
def read_data():
    return ["a", "bb", "ccc", "dd", "eeeee", "f"]


def filter_short(words):
    return (word for word in words if len(word) >= 2)


def map_to_upper(words):
    return (word.upper() for word in words)


def write_data(words):
    for word in words:
        print(word)


if __name__ == "__main__":
   …
12 0 Open
Comprehensions & generators medium

How to Build a Backpressure Generator Pause Producer Demo in Python

Demonstrates a producer–consumer pattern with a fixed-size buffer that pauses production when full, simulating backpressure.

backpressure producer-consumer deque
Python
import time
import collections

def producer(buffer, max_size, items):
    """Adds items to the buffer until full, then pauses."""
    for item in items:
        while len(buffer) >= max_size:
            print(f"Buffer full ({len(buffer)}/{max_size}) — producer paused")
            time.sleep(0.1)
        buffer.appe…
14 0 Open
Comprehensions & generators medium

How to Generate Primes with a Generator in Python

Generate prime numbers up to a limit using the Sieve of Eratosthenes wrapped in a generator expression for lazy evaluation.

generators sieve primes
Python
def prime_generator(limit):
    sieve = [True] * (limit + 1)
    sieve[0] = sieve[1] = False

    for i in range(2, int(limit ** 0.5) + 1):
        if sieve[i]:
            for j in range(i * i, limit + 1, i):
                sieve[j] = False

    return (num for num, is_prime in enumerate(sieve) if is_prime)


if __n…
15 0 Open
Comprehensions & generators medium

How to Send Values into a Python Generator Coroutine

Use the .send() method to pass values into a running generator coroutine and capture them.

generators coroutines yield
Python
def coroutine():
    received = []
    while True:
        value = yield
        received.append(value)
        print(f"Coroutine received: {value}")
        if value == "stop":
            break
    return received

if __name__ == "__main__":
    gen = coroutine()
    next(gen)  # Prime the generator
    gen.send("he…
13 0 Open
Comprehensions & generators medium

How to filter a generator with a predicate function in Python

This code defines a generator function that yields only items from an iterable that satisfy a given predicate, then tests it with even and positive number filters.

generators filtering lazy evaluation
Python
def filter_gen(predicate, iterable):
    for item in iterable:
        if predicate(item):
            yield item

def is_even(num):
    return num % 2 == 0

def is_positive(num):
    return num > 0

if __name__ == "__main__":
    numbers = range(-5, 10)
    
    even_numbers = list(filter_gen(is_even, numbers))
    p…
10 0 Open
Comprehensions & generators medium

How to stream parse JSON arrays in Python

This code demonstrates two generators: one that streams a JSON array as individual chunks, and another that incrementally parses those chunks into Python objects using json.JSONDecoder.

json generator streaming
Python
import json


def json_array_stream(items):
    """Generator that yields JSON-encoded values one at a time."""
    yield "["
    for i, item in enumerate(items):
        if i > 0:
            yield ","
        yield json.dumps(item)
    yield "]"


def parse_json_stream(stream):
    """Consumes a stream of JSON fragme…
14 0 Open
Streaming & messaging medium

How to Stream Join Windowed Mock Topics in Python

Simulates two message topics and joins their events when timestamps fall within a sliding time window using Python generators and deques.

streaming join generator
Python
import itertools
import random
import time
from collections import deque
from dataclasses import dataclass, field

@dataclass
class Event:
    key: str
    value: int
    timestamp: float = field(default_factory=time.time)

def generate_topic(prefix, keys, start_time):
    while True:
        yield Event(
            …
14 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.