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__":
…
Convert Data in Python with Comprehensions and Generators
Convert mixed data to integers, filter and transform numbers, and extract fields from dicts using list comprehensions and generator expressions.
def convert_numbers(data):
"""Convert a list of mixed values into integers using a comprehension."""
return [int(item) for item in data if item is not None]
def double_even_numbers(numbers):
"""Double only even numbers using a generator expression."""
return (n * 2 for n in numbers if n % 2 == 0)
d…
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 Filter Data with Predicates in Python
This helper filters a list with a predicate using a list comprehension, plus a lazy generator version that yields matches one by one.
def filter_data(data, predicate):
"""Return a list containing only items that pass the predicate."""
return [item for item in data if predicate(item)]
def filter_data_lazy(data, predicate):
"""Generator version: yields items that pass the predicate one by one."""
for item in data:
if predicat…
How to Parse Data with Generators and Comprehensions in Python
This code demonstrates using a generator expression to filter active users and a dictionary comprehension to aggregate scores by name.
def parse_data_helper(raw_records):
"""Extract active users' names and scores from raw records."""
parsed = (
(record["name"], record["score"])
for record in raw_records
if record["active"] and record["score"] >= 0
)
return list(parsed)
def aggregate_scores(parsed_data):
"…
How to Use Comprehensions and Generators to Check Data in Python
A beginner-friendly helper that filters numeric values, computes squares and cubes with comprehensions and a generator, and returns a summary dictionary.
def check_data(iterable):
"""Return a summary of numeric data using comprehensions and a generator."""
values = [item for item in iterable if isinstance(item, (int, float))]
squares = [x ** 2 for x in values if x > 0]
cubes = (x ** 3 for x in values if x > 0)
cube_list = list(cubes)
return {
…
How to Use List Comprehensions and Generators to Format Data in Python
A beginner-friendly helper that formats dictionaries into strings using a list comprehension and generates squared numbers lazily with a generator.
def format_data(items):
"""Format a list of dictionaries into readable strings."""
formatted = [
f"{item.get('name', 'Unknown')}: {item.get('value', 0)} units"
for item in items
if item.get('value', 0) > 0
]
return formatted if formatted else ["No positive values found"]
def g…
How to Use List Comprehensions and Generators to Transform Data in Python
Transform a list of integers by squaring even numbers with a list comprehension and cubing odd numbers with a generator.
def transform_data(data):
"""
Transform a list of integers:
- squares of even numbers using a list comprehension
- cubes of odd numbers using a generator
"""
squares = [num ** 2 for num in data if num % 2 == 0]
cubes = (num ** 3 for num in data if num % 2 != 0)
return squares, cubes
i…
How to Validate Data with Python Comprehensions and Generators
Use list, generator, and dictionary comprehensions to filter and transform data for quick validation in Python.
def validate_integer(data):
return [item for item in data if isinstance(item, int)]
def validate_positive(numbers):
return (num for num in numbers if num > 0)
def validate_string_lengths(data, min_length=3):
return {item: len(item) for item in data if isinstance(item, str) and len(item) >= min_length}
i…
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 filter even numbers with a Python list comprehension
Build a new list of only the even numbers from 1 to 20 using a single list comprehension with a filter condition.
even_numbers = [num for num in range(1, 21) if num % 2 == 0]
print(even_numbers)
How to skip items until a condition is met in Python
Use itertools.dropwhile to skip leading elements while a predicate returns true, then yield the rest of the sequence unchanged.
def is_negative(x):
return x < 0
numbers = [-3, -1, 0, 5, 2, -8, 7]
result = list(itertools.dropwhile(is_negative, numbers))
print(f"Original: {numbers}")
print(f"After dropwhile: {result}")
List Comprehension to Filter Even Numbers in Python
Creates a new list containing only the even numbers from an existing list using a list comprehension with a condition.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [n for n in numbers if n % 2 == 0]
print(f"Original: {numbers}")
print(f"Even numbers: {even_numbers}")
Merge Data with Comprehension and Generator in Python
Merge user and order data using a dictionary comprehension for lookups and a generator expression to filter and transform orders.
def merge_data(users, orders):
"""
Merge user and order data using a dictionary comprehension
and a generator expression for filtering.
"""
# Build a lookup: user_id -> user name
user_map = {user["id"]: user["name"] for user in users}
# Generator: yield orders with user names attached
…
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)
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.