Comprehensions & generators
List/dict/set comprehensions, generator expressions, and lazy iteration.
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.
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__":
…
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.
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…
How to Create a Generator Context Manager in Python with contextlib
Create a custom context manager with the @contextlib.contextmanager decorator to manage resources using a generator function.
import contextlib
@contextlib.contextmanager
def temporary_directory():
"""Yield a string and clean up after the block exits."""
print("Creating temp directory...")
dir_name = "/tmp/example"
try:
yield dir_name
finally:
print(f"Removing {dir_name}...")
if __name__ == "__main__":
…
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.
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…
How to Send Values into a Python Generator Coroutine
Use the .send() method to pass values into a running generator coroutine and capture them.
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…
How to Throw an Exception into a Python Generator
This code demonstrates how to use the .throw() method on a generator to inject an exception at its current yield point and let it recover gracefully.
def demo_throw_into_generator():
"""Demonstrate throwing an exception into a running generator."""
def counter():
"""Generator that counts until interrupted."""
try:
i = 0
while True:
yield i
i += 1
except ValueError as e:
…
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.
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…
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.
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…
Merge Sorted Iterators with a Heap Generator in Python
Merge multiple sorted iterators into a single sorted stream using a heap and generator, yielding values lazily in order.
import heapq
def merge_sorted_iterators(*iterators):
heap = []
for idx, iterator in enumerate(iterators):
try:
value = next(iterator)
heapq.heappush(heap, (value, idx, iterator))
except StopIteration:
continue
while heap:
value, idx, iterator = …
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.