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__":
…
Build a lazy generator to read file lines in Python
Create a generator function that yields file lines one at a time, avoiding loading the entire file into memory, and demonstrate its lazy processing.
def lazy_lines(filepath):
"""Yield lines from a file one at a time without loading the whole file into memory."""
with open(filepath, 'r', encoding='utf-8') as file:
for line in file:
yield line.rstrip('\n')
if __name__ == "__main__":
# Create a sample file to demonstrate
sample_c…
Chunk an Iterable into Batches with a Generator in Python
Yield fixed-size batches from any iterable lazily using itertools.islice inside a generator function.
from itertools import islice
def chunked(iterable, size):
iterator = iter(iterable)
while True:
batch = list(islice(iterator, size))
if not batch:
break
yield batch
if __name__ == "__main__":
data = range(10)
for batch in chunked(data, 3):
print(batch)
Flatten a Nested List in Python (Recursive Generator)
Recursively flatten arbitrarily nested lists into a single-level list using both a function and a generator with `yield from`.
def flatten(nested_list):
"""Recursively flatten a nested list into a single-level list."""
result = []
for item in nested_list:
if isinstance(item, list):
result.extend(flatten(item))
else:
result.append(item)
return result
def flatten_generator(nested_list):
…
Generate UUID4 Values with a Python Generator
This code defines a generator function that yields mock UUID4 values, allowing you to stream unique identifiers one at a time.
import uuid
def generate_uuids(count=5):
"""Generate a stream of mock UUID4 values."""
for _ in range(count):
yield uuid.uuid4()
if __name__ == "__main__":
# Generate and print 5 UUIDs
for uid in generate_uuids(5):
print(uid)
Generator Function to Yield an Infinite Counter in Python
This code demonstrates a generator function that yields an infinite sequence of integers starting from a given value, allowing lazy, memory-efficient iteration.
def infinite_counter(start=0):
count = start
while True:
yield count
count += 1
if __name__ == "__main__":
counter = infinite_counter(5)
for _ in range(5):
print(next(counter))
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 Combinations with Replacement in Python
Generate all r-length combinations with repetition from a list using the standard library itertools.combinations_with_replacement function.
from itertools import combinations_with_replacement
items = ['A', 'B', 'C']
r = 2
combos = list(combinations_with_replacement(items, r))
for combo in combos:
print(combo)
if __name__ == "__main__":
print(f"Total combinations with replacement: {len(combos)}")
How to Generate Fibonacci Numbers in Python Without Recursion
Build an efficient infinite Fibonacci sequence using a generator function with O(1) memory and no recursion overhead.
def fib(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
if __name__ == "__main__":
count = 10
result = list(fib(count))
print(result)
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 Merge Multiple Iterables with a Generator in Python
This code defines a generator function that 'chains' or merges multiple iterables into a single iterator, which is then converted to a list.
def chain(*iterables):
for iterable in iterables:
yield from iterable
def main():
list1 = [1, 2, 3]
tuple1 = (4, 5)
set1 = {6, 7}
string1 = "89"
result = list(chain(list1, tuple1, set1, string1))
print(result)
if __name__ == "__main__":
main()
How to Sort Data with Comprehensions and Generators in Python
Sort a list of tuples by a key, then use a list comprehension to extract names and a generator to square high ranks.
data = [("Anna", 3), ("Ben", 1), ("Clara", 2), ("Dan", 5), ("Eve", 4)]
# Comprehension: list of tuples (name, rank) sorted ascending by rank
sorted_by_rank = sorted(data, key=lambda x: x[1])
# Comprehension: extract just the names in rank order
names_in_rank_order = [name for name, rank in sorted_by_rank]
# Generat…
How to Use Comprehensions and Generators in Python
Demonstrate list, set, and dictionary comprehensions plus generator expressions and generator functions in one beginner-friendly script.
def demonstrate_comprehensions_generators():
# List comprehension: transform and filter in one line
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squares = [num ** 2 for num in numbers if num % 2 == 0]
print(f"Square of even numbers (list comprehension): {squares}")
# Set comprehension: unique values
…
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)
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…
Python Comprehensions and Generators for Beginners
Learn list, dict, and set comprehensions plus generator expressions and generator functions with clear, runnable examples.
# Demonstrates list comprehensions, dict comprehensions, set comprehensions, and generators
def demonstrate_comprehensions():
# List comprehension: squares of even numbers
numbers = range(1, 11)
even_squares = [n ** 2 for n in numbers if n % 2 == 0]
# Dict comprehension: number to its factorial
…
Python Generator to Filter Duplicates with a Seen Set
A lazily-evaluated generator function that yields only the first occurrence of each item, using a set to track seen values.
def unique_generator(items):
seen = set()
for item in items:
if item not in seen:
seen.add(item)
yield item
if __name__ == "__main__":
data = [1, 2, 2, 3, 3, 3, 4, 5, 5]
result = list(unique_generator(data))
print(result)
Write Data Helpers with Comprehensions and Generators in Python
Demonstrates list, dict, and set comprehensions plus generator expressions and generator functions for building concise data helpers.
# Basic comprehensions and generators demo
# List comprehension: squares of evens
squares = [x * x for x in range(10) if x % 2 == 0]
print("List comp:", squares)
# Dictionary comprehension: char -> count
text = "hello"
char_counts = {c: text.count(c) for c in set(text)}
print("Dict comp:", char_counts)
# Set compre…
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.