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.
Python code
20 linesdef 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))
positive_numbers = list(filter_gen(is_positive, numbers))
print(f"Numbers: {list(numbers)}")
print(f"Even numbers: {even_numbers}")
print(f"Positive numbers: {positive_numbers}")
Output
Numbers: [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Even numbers: [-4, -2, 0, 2, 4, 6, 8]
Positive numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9]
How it works
The filter_gen function is a generator, so it yields one item at a time instead of building a full list in memory. Each call to predicate(item) evaluates to True or False, and only items that return True are yielded. Laziness means the filtering happens only as you iterate, which is efficient for large data. The list() call around the generator converts the yielded items into a concrete list for printing.
Common mistakes
- Forgetting that a generator can only be iterated once, so reusing it after `list()` yields nothing.
- Passing a function call like `is_even()` instead of the function reference `is_even`.
- Assuming the predicate must return a boolean—truthy values also work.
- Not converting the generator to a list before printing, which shows a generator object instead of values.
Variations
- Use Python's built-in `filter(predicate, iterable)` to achieve the same result.
- Use a generator expression: `(item for item in iterable if predicate(item))`.
Real-world use cases
- Filtering streaming log lines that match a severity threshold in a real-time monitoring pipeline.
- Processing large data files line-by-line, keeping only records that pass validation criteria.
- Selecting valid user inputs from a form submission without loading all values into memory.
Sponsored
More from Comprehensions & generators
- Batch Rows in Chunks with a Generator in Python easy
- Build a Generator Pipeline in Python: Filter Then Map medium
- Build a lazy generator to read file lines in Python easy
- Chunk an Iterable into Batches with a Generator in Python easy
- Convert Data in Python with Comprehensions and Generators easy
- Count Data in Python with Comprehensions and Generators easy
Keep learning
Related tutorials and quizzes for this topic.