Comprehensions & generators
List/dict/set comprehensions, generator expressions, and lazy iteration.
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.
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)
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.
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")))
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.