Comprehensions & generators
List/dict/set comprehensions, generator expressions, and lazy iteration.
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.
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)
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")))
How to Group Data in Python with defaultdict and Comprehensions
Group a list of items by a computed key using a defaultdict-based generator helper and an alternative dictionary comprehension approach.
from collections import defaultdict
def group_by(data, key_func):
"""Group items in data by the value returned by key_func."""
result = defaultdict(list)
for item in data:
result[key_func(item)].append(item)
return dict(result)
def group_by_comprehension(data, key_func):
"""Same grouping …
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.
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:
…
Normalize Data in Python with Comprehensions and Generators
Clean a list by dropping None values with a comprehension, then min-max normalize it using a lazy generator expression — a beginner-friendly data preparation pattern.
import statistics
# Sample raw data including missing and outlier-ish values
raw = [22, 18, None, 25, 30, 19, 22, 17, None, 28, 24]
# Clean the data: drop None values using a list comprehension
clean = [x for x in raw if x is not None]
# Normalize using min-max scaling with a generator expression
min_val = min(clea…
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.