Reference library

Comprehensions & generators

List/dict/set comprehensions, generator expressions, and lazy iteration.

2 matches
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"},
      …
15 0 Open
Comprehensions & generators easy

How to Split Data into Chunks and Use Generators in Python

Split a list into fixed-size chunks with a list comprehension and square even numbers lazily with a generator expression.

comprehensions generators chunking
Python
def split_numbers(data, chunk_size):
    return [data[i:i + chunk_size] for i in range(0, len(data), chunk_size)]


def square_even_numbers(numbers):
    return (n ** 2 for n in numbers if n % 2 == 0)


if __name__ == "__main__":
    sample_data = list(range(1, 21))
    chunks = split_numbers(sample_data, 5)
    print…
15 0 Open

Browse by section

Each section groups closely related Python snippets.

Comprehensions & generators — Python code examples

What you will find here

This page collects comprehensions & generators snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

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.