Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

53 matches
Functions & basics easy

Chain Generators with yield from in Python

Combine multiple generators into one seamless sequence using the `yield from` delegation syntax in Python.

generators yield delegation
Python
def numbers():
    yield 1
    yield 2
    yield 3

def letters():
    yield 'a'
    yield 'b'
    yield 'c'

def combined():
    yield from numbers()
    yield from letters()

if __name__ == "__main__":
    print(list(combined()))
13 0 Open
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…
14 0 Open
Files & data easy

How to Walk a Directory Tree with os.walk in Python

A generator function that recursively walks a directory tree and yields every file path found using the os.walk generator.

os.walk generators directory-tree
Python
import os


def walk_directory_tree(root_path: str):
    """Walk a directory tree and yield file paths using os.walk generator."""
    for dirpath, dirnames, filenames in os.walk(root_path):
        for filename in filenames:
            yield os.path.join(dirpath, filename)


if __name__ == "__main__":
    # Create a…
11 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, …
12 0 Open
Comprehensions & generators easy

Batch Rows in Chunks with a Generator in Python

Group a list of row dicts into fixed-size chunks using a generator that yields one slice per call.

generators chunking database
Python
from typing import Iterator, List


def batch_rows(rows: List[dict], batch_size: int) -> Iterator[List[dict]]:
    for i in range(0, len(rows), batch_size):
        yield rows[i:i + batch_size]


if __name__ == "__main__":
    sample_rows = [
        {"id": 1, "name": "Alice"},
        {"id": 2, "name": "Bob"},
      …
14 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 easy

Chunk an Iterable into Batches with a Generator in Python

Yield fixed-size batches from any iterable lazily using itertools.islice inside a generator function.

generators iterators itertools
Python
from itertools import islice

def chunked(iterable, size):
    iterator = iter(iterable)
    while True:
        batch = list(islice(iterator, size))
        if not batch:
            break
        yield batch

if __name__ == "__main__":
    data = range(10)
    for batch in chunked(data, 3):
        print(batch)
14 0 Open
Comprehensions & generators easy

Convert Data in Python with Comprehensions and Generators

Convert mixed data to integers, filter and transform numbers, and extract fields from dicts using list comprehensions and generator expressions.

comprehensions generators list-comprehension
Python
def convert_numbers(data):
    """Convert a list of mixed values into integers using a comprehension."""
    return [int(item) for item in data if item is not None]


def double_even_numbers(numbers):
    """Double only even numbers using a generator expression."""
    return (n * 2 for n in numbers if n % 2 == 0)


d…
14 0 Open
Comprehensions & generators easy

Count Data in Python with Comprehensions and Generators

Count list items with a dict comprehension and generate squares lazily with a generator expression, printing both results.

comprehensions generators counter
Python
from collections import Counter

data = ["apple", "banana", "apple", "cherry", "banana", "apple"]

counts = {item: data.count(item) for item in set(data)}

square_gen = (x * x for x in range(5))
squares = list(square_gen)

if __name__ == "__main__":
    print("Manual count:", counts)
    print("Counter:", dict(Counter…
14 0 Open
Comprehensions & generators easy

Cycle an iterable forever in Python

Define a generator that repeatedly yields items from an iterable, cycling back to the beginning infinitely.

generators cycle iteration
Python
def cycle_generator(iterable):
    """Yield items from iterable forever, cycling back to the start."""
    items = list(iterable)  # Convert to list so it can restart
    index = 0
    while True:
        yield items[index]
        index = (index + 1) % len(items)


if __name__ == "__main__":
    colors = ["red", "gre…
14 0 Open
Comprehensions & generators easy

Drop n items then yield rest generator

A generator that skips the first n items of an iterable and then yields the remaining items one by one.

generators iterators drop
Python
def drop(n, items):
    """Yield every item except the first n from items."""
    it = iter(items)
    for _ in range(n):
        next(it, None)  # skip first n items
    yield from it


if __name__ == "__main__":
    numbers = [10, 20, 30, 40, 50]
    result = list(drop(2, numbers))
    print(result)
10 0 Open
Comprehensions & generators easy

Enumerate a Generator With a Running Total in Python

A generator that yields each element with its index and a cumulative sum, letting you track a running total as you iterate.

generators enumerate running-total
Python
def running_total_enum(iterable):
    """Yields (index, item, running_total) for each element."""
    total = 0
    for index, item in enumerate(iterable):
        total += item
        yield index, item, total

if __name__ == "__main__":
    numbers = [10, 20, 30, 40, 50]
    for idx, value, running_sum in running_to…
13 0 Open
Comprehensions & generators easy

Flatten a Nested List in Python (Recursive Generator)

Recursively flatten arbitrarily nested lists into a single-level list using both a function and a generator with `yield from`.

recursion generators flatten
Python
def flatten(nested_list):
    """Recursively flatten a nested list into a single-level list."""
    result = []
    for item in nested_list:
        if isinstance(item, list):
            result.extend(flatten(item))
        else:
            result.append(item)
    return result


def flatten_generator(nested_list):
…
13 0 Open
Comprehensions & generators easy

Generate Data with Python Comprehensions and Generators

Shows list, dict compregensions and generator expressions plus a Fibonacci generator to produce data lazily.

comprehensions generators lazy-evaluation
Python
# Data generation helpers using comprehensions and generators
from itertools import islice


def fibonacci(limit):
    """Generate Fibonacci numbers up to a limit."""
    a, b = 0, 1
    while a <= limit:
        yield a
        a, b = b, a + b


def main():
    # List comprehension: squares of even numbers
    square…
14 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)
14 0 Open
Comprehensions & generators easy

Generator Function to Yield an Infinite Counter in Python

This code demonstrates a generator function that yields an infinite sequence of integers starting from a given value, allowing lazy, memory-efficient iteration.

generators infinite sequences yield
Python
def infinite_counter(start=0):
    count = start
    while True:
        yield count
        count += 1

if __name__ == "__main__":
    counter = infinite_counter(5)
    for _ in range(5):
        print(next(counter))
13 0 Open
Comprehensions & generators easy

Group Consecutive Keys in Python with itertools.groupby

Group consecutive equal elements in a list using the itertools.groupby generator, printing each key and its values.

itertools groupby generators
Python
from itertools import groupby

data = [1, 1, 2, 2, 3, 1, 1, 4, 4, 4]

for key, group in groupby(data):
    group_list = list(group)
    print(f"Key: {key}, Values: {group_list}")
10 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…
13 0 Open
Comprehensions & generators easy

How to Build a Sliding Window Generator in Python

Create a generator that yields fixed-size overlapping slices of a sequence, useful for efficient windowed iteration.

generators sliding-window iteration
Python
def sliding_window(sequence, size):
    for i in range(len(sequence) - size + 1):
        yield sequence[i:i + size]

if __name__ == "__main__":
    data = [1, 2, 3, 4, 5]
    n = 3
    for window in sliding_window(data, n):
        print(window)
11 0 Open
Comprehensions & generators easy

How to Close a Generator and Handle GeneratorExit in Python

This Python code demonstrates how to explicitly close a generator using the close() method and handle the GeneratorExit exception through a finally block to run cleanup logic.

generators generator-exit close
Python
def countdown(n):
    try:
        while n > 0:
            yield n
            n -= 1
    finally:
        print(f"Generator closed after countdown completed")


if __name__ == "__main__":
    gen = countdown(5)
    print(next(gen))
    print(next(gen))
    gen.close()
    print("Generator closed explicitly")
11 0 Open
Comprehensions & generators easy

How to Compress a Generator with a Boolean Mask in Python

Filters items from a generator based on a parallel boolean mask, yielding only the items where the mask is True.

generators zip filter
Python
def compress(generator, mask):
    for item, keep in zip(generator, mask):
        if keep:
            yield item


if __name__ == "__main__":
    data = [1, 2, 3, 4, 5]
    mask = [True, False, True, False, True]
    result = list(compress(iter(data), mask))
    print(result)
13 0 Open
Comprehensions & generators easy

How to Create a Pairwise Generator with zip and tee in Python

Build a memory-efficient generator that yields successive overlapping pairs from any iterable using zip and tee.

itertools generators zip
Python
from itertools import tee


def pairwise(iterable):
    """Yield successive overlapping pairs from iterable."""
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)


if __name__ == "__main__":
    values = [1, 2, 3, 4, 5]
    print(list(pairwise(values)))
    print(list(pairwise("hello")))
14 0 Open
Comprehensions & generators easy

How to Create an Infinite Arithmetic Sequence Generator in Python

Build a memory-efficient generator that yields an infinite arithmetic progression and extract the first N values with list comprehension.

generators yield infinite-sequences
Python
"""Count generator infinite arithmetic progression"""


def arithmetic_counter(start=0, step=1):
    """Generate an infinite arithmetic sequence."""
    current = start
    while True:
        yield current
        current += step


if __name__ == "__main__":
    counter = arithmetic_counter(1, 3)
    result = [next(c…
13 0 Open
Comprehensions & generators easy

How to Delegate Iteration to a Subgenerator with yield from in Python

Use yield from to delegate iteration from one generator to a subgenerator, flattening nested generator output into a single sequence.

generators yield-from delegation
Python
def subgenerator():
    yield "first"
    yield "second"
    yield "third"


def delegate():
    yield "before delegation"
    yield from subgenerator()
    yield "after delegation"


if __name__ == "__main__":
    for item in delegate():
        print(item)
12 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.