Reference library

Comprehensions & generators

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

1 match
Comprehensions & generators easy

How to Lazily Transform Items in Python with a Generator

Map a transform function over an iterable lazily with a generator so items are processed on demand, not up front.

generators lazy evaluation mapping
Python
def lazy_map(items, transform):
    for item in items:
        yield transform(item)

def double(x):
    return x * 2

def upper(s):
    return s.upper()

if __name__ == "__main__":
    numbers = [1, 2, 3, 4, 5]
    doubled = lazy_map(numbers, double)
    print("Doubled numbers:", end=" ")
    for value in doubled:
  …
14 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.