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__":
…
Dict Comprehension to Map Keys to Lengths in Python
Build a dictionary that maps each word to its character count using a dictionary comprehension.
words = ["apple", "banana", "cherry", "date", "elderberry"]
word_lengths = {word: len(word) for word in words}
print(word_lengths)
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:
…
How to Use starmap() to Unpack Tuple Arguments in Python
Use itertools.starmap to apply a function to each tuple in an iterable, unpacking tuple elements as separate arguments and returning an iterator of results.
from itertools import starmap
def multiply(a, b):
return a * b
if __name__ == "__main__":
pairs = [(2, 3), (4, 5), (6, 7), (8, 9)]
results = list(starmap(multiply, pairs))
print(results)
Memory efficient map over large file in Python
A generator-based streaming map that processes a large file line by line without loading the whole file into memory.
import sys
def process_lines(file_path):
"""Memory-efficient map over a large file: yields processed lines."""
with open(file_path, 'r') as f:
for line in f:
# Example mapping: strip whitespace and uppercase
yield line.strip().upper()
if __name__ == "__main__":
# Use a sma…
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.